问题描述
我在用JAVA编写基本的Web服务器时遇到了一些麻烦.目前,它在传递html或css文件方面运行良好.但是,当涉及到图像时,事情就变得混乱了.我认为读取图像文件并准备将其发送时做错了事.但是看一下代码:
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()]
但是chrome无法正确显示图像,而歌剧也无法全部显示!我曾经使用BufferedReader读取文件,但发现有人说BufferedReader无法正确处理二进制数据,因此我尝试使用FileInputStream,但问题仍然相同):
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 (:
推荐答案
您必须同时使用流:输入流和输出流.读者和作家假定内容为Unicode,并对字节流进行调整.当然,PrintWriter是作家.
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.
这篇关于如何在JAVA中创建HTTP响应发送图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!