【发布时间】:2020-06-06 15:23:10
【问题描述】:
我有一个简单的 Java Web 服务器,我试图用它在浏览器中显示图像。
到目前为止,我拥有它,因此当转到 localhost:7500/image2.jpg 时,它会下载图像而不是在浏览器中显示它
当转到 gif 扩展 (localhost:7500/image33.gif) 时,它只显示一个黑色的小方块。
这是我到目前为止所做的:
public void getType(File f, String path, BufferedReader bfr)
{
String extention = path.substring(path.lastIndexOf("/") + 1);
try {
if (extention == "gif")
{
String line;
String httpResponse = "HTTP/1.1";
httpResponse += " 200 OK \n";
httpResponse += "Content-Type: image/gif\n" ;
httpResponse += "Content-Length: " + f.length()+"\n\n";
serverClient.getOutputStream().write(httpResponse.getBytes("UTF-8"));
//loop to print each line of file to browser
while ((line = bfr.readLine()) != null)
{
serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}
}
else if (extention == "jpg")
{
String line;
String httpResponse = "HTTP/1.1";
httpResponse += " 200 OK \n";
httpResponse += "Content-Type: image/jpg\n" ;
httpResponse += "Content-Length: " + f.length()+"\n\n";
serverClient.getOutputStream().write(httpResponse.getBytes("UTF-8"));
//loop to print each line of file to browser
while ((line = bfr.readLine()) != null)
{
serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}
}
else
{
String line;
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
serverClient.getOutputStream().write(httpResponse.getBytes("UTF-8"));
//loop to print each line of file to browser
while ((line = bfr.readLine()) != null)
{
serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}
}
}catch(Exception ex)
{
//when page is loaded, print confirmation to system
System.out.println("999999999");
}
}
【问题讨论】:
标签: java sockets http-headers webserver