简体   繁体   English

如何在JAVA中创建发送图像的HTTP响应?

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

I'm occurring some trouble writing a basic webserver in JAVA. 我在JAVA中编写基本的Web服务器时遇到了一些麻烦。 It's currently working fine at delivering html or css files. 目前它正在提供html或css文件。 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! 但是Chrome没有正确显示图像而且歌剧不会显示出来! 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 ): 我曾经用BufferedReader读取文件,但我发现有人说BufferedReader无法正确处理二进制数据所以我尝试使用FileInputStream,但问题保持不变):

Thanks for any hints and help in advance (: 感谢您提前提供的任何提示和帮助(:

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. 读者和编写者假设内容是Unicode并对字节流进行调整。 PrintWriter is, of course, a writer. PrintWriter当然是作家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM