How to create a HTTP-response sending an image in JAVA?

喜你入骨 提交于 2021-01-29 13:17:26

问题


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:

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;
}

So my browser receives something like:

HTTP/1.0 200 OK
Content-type: image/jpeg

[String that was read in readFile()]

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 ):

Thanks for any hints and help in advance (:


回答1:


You must use streams on both sides: input stream and output stream. Readers and writers assume the content is Unicode and make adjustments to the byte stream. PrintWriter is, of course, a writer.



来源:https://stackoverflow.com/questions/7956849/how-to-create-a-http-response-sending-an-image-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!