如何用JAVA创建发送图像的HTTP响应?
我在用JAVA编写基本Web服务器时遇到了一些问题。它目前在交付html或css文件方面运行良好。但当涉及到图像时,事情就一团糟了。我假设我在读取图像文件并准备发送时出错了。但请看一下代码:如何用JAVA创建发送图像的HTTP响应?,java,image,http,webserver,response,Java,Image,Http,Webserver,Response,我在用JAVA编写基本Web服务器时遇到了一些问题。它目前在交付html或css文件方面运行良好。但当涉及到图像时,事情就一团糟了。我假设我在读取图像文件并准备发送时出错了。但请看一下代码: public void launch() { while(true) { try { Socket connection = this.server_socket.accept(); ...
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;
}
因此,我的浏览器接收到如下信息:
HTTP/1.0 200 OK
Content-type: image/jpeg
[String that was read in readFile()]
但是chrome没有正确显示图像,opera也不会全部显示!我以前用BufferedReader读取文件,但我发现有人说BufferedReader无法正确处理二进制数据,因此我尝试使用FileInputStream,但问题仍然存在):
感谢您提前提供的提示和帮助(:您必须同时使用流:输入流和输出流。读卡器和写卡器假定内容为Unicode,并对字节流进行调整。当然,PrintWriter是一个写卡器