title: Image Responses in Java - HTTPServer
body: <p>I have a web server in java like this:</p>
  
  <pre><code>public static void main(String[] args) throws Exception {
     HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
     server.createContext("/", new HomeHandler());
     server.setExecutor(null); // creates a default executor
     server.start();
  }
  </code></pre>
  
  <p>And here's the <code>HomeHandler</code>:</p>
  
  <pre><code>class HomeHandler implements HttpHandler {
      public void handle(HttpExchange t) throws IOException {
      String filepath = "C:\\Public\\home.html";
          String response = getPage(filepath);
          t.sendResponseHeaders(200, response.length());
          OutputStream os = t.getResponseBody();
          os.write(response.getBytes());
          os.close();
      }
  }
  </code></pre>
  
  <p>and finally here's the function <code>getPage()</code>:</p>
  
  <pre><code>private static String getPage(String page){
      String toret = "";
      BufferedReader br = null;
      try {
          String sCurrentLine;
          br = new BufferedReader(new FileReader(page));
          while ((sCurrentLine = br.readLine()) != null) {
              toret += sCurrentLine;
          }
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          try {
              if (br != null) br.close();
          } catch (IOException ex) {
              ex.printStackTrace();
          }
      }
      return toret;
  }
  </code></pre>
  
  <p>But when my home page loads, it has an image in it so the browser makes another request to my server for the image, I made a similar handler for images which does the same thing, i.e, calls the function getPage() passing in as arguments the image's filepath...</p>
  
  <p>But when it actually runs in the browser it doesn't show the image. But it correctly tells the size of the image when I open the image alone in the new tab (Google Chrome is my Browser, the latest one as of today)..</p>