title: How to create a HTTP-response sending an image in JAVA?
body: <p>I'm occurring some trouble writing a basic webserver in JAVA. It's currently working fine at delivering html or css files. But when it comes to images things are messed up. I assume I'm doing something wrong at reading the image-files and preparing them to be sent. But have a look at the code:</p>
  
  <pre><code>public void launch()
  {
      while(true)
      {
          try
          {
               Socket connection = this.server_socket.accept();
  
               ...
  
               PrintWriter print_writer = new PrintWriter(connection.getOutputStream());
  
               String response = this.readFile(this.request_header.get("Resource"));
               print_writer.print(response);
  
               print_writer.flush();
               connection.close();
           }
           catch(...)
           {
               ...
           }
      }
  }
  
  private String readFile(String path)
  {
      try
      {
           ...
  
           FileInputStream file_input_stream = new FileInputStream(path);         
           int bytes = file_input_stream.available();
           byte[] response_body = new byte[bytes];
  
           file_input_stream.read(response_body);
           this.response_body = new String(response_body);
  
           file_input_stream.close();
  
           this.setResponseHeader(200, file_ext);
  
           this.response_header = this.response_header + "\r\n\r\n" + this.response_body;
      }
      catch(...)
      {
           ...
      }
  
      return this.response_header;
  }
  </code></pre>
  
  <p>So my browser receives something like:</p>
  
  <pre><code>HTTP/1.0 200 OK
  Content-type: image/jpeg
  
  [String that was read in readFile()]
  </code></pre>
  
  <p>But chrome's not displaying the image correctly and opera won't show it all! I used to read the file with an BufferedReader but I found someone saying that the BufferedReader can't handle binary data properly so I tried with the FileInputStream, but the problem stayed the same ):</p>
  
  <p>Thanks for any hints and help in advance (:</p>