gpt4 book ai didi

java - 为 Java HTTP 服务器构建 http header

转载 作者:太空宇宙 更新时间:2023-11-04 15:15:26 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的 HTTP 服务器来处理来自浏览器的请求并返回适当的答案。我已经实现了基本连接,但在正确构建返回 header 以便浏览器可以显示来自服务器的答案时遇到了困难(例如,从服务器获取 .jpg 图片并正确显示)。

我认为我遇到的问题与未正确构建答案 header 有关。我对此缺乏经验,希望得到任何帮助。

下面是我的 HttpHandler 类,它处理来自浏览器的请求并返回答案。我认为问题出在 httpHeaderConstructor 方法中的某个地方。

  package Server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.io.FilenameUtils;

public class HttpHandler {

public static void httpHandler(BufferedReader clientInput, DataOutputStream serverResponse){

int type_of_method = 0;

String path = new String();

try{

String tmp = clientInput.readLine();
String tmp2 = new String(tmp);

tmp.toUpperCase();

System.out.println("Clients request call:" + tmp);

if(tmp.startsWith("GET"))
type_of_method = 1;

if(type_of_method == 0){
try{
serverResponse.writeBytes(httpHeaderConstructor(501, 0));
serverResponse.close();
return;

}catch(Exception e){
System.out.println("1.Error: " + e.getMessage());
}
}

int start = 0;
int end = 0;

for(int a = 0; a < tmp2.length(); a++){
if(tmp2.charAt(a) == ' ' && start != 0){
end = a;
break;
}
if(tmp2.charAt(a) == ' ' && start == 0){
start = a;
}
}

path = tmp2.substring(start + 2, end);
System.out.println("Requested file path: " + path);

}catch(Exception e){
System.out.println("2.Error (bad request Exception): " + e.getMessage());
}

System.out.println("Client requested: " + new File(path).getAbsolutePath());

sendRequestedFile(path, serverResponse);

}

private static void sendRequestedFile(String filePath, DataOutputStream srvResponse){

FileInputStream requestedFile = null;

try{

requestedFile = new FileInputStream(filePath);
System.out.println("File found and opened successfully");

}catch(Exception e){

try {

System.out.println("Could not find file!");
srvResponse.writeBytes(httpHeaderConstructor(404, 0));
srvResponse.close();

} catch (Exception err) {
System.out.print("Error: Can't send failed response!");
System.out.print("Error message: " + err.getMessage());

}
}

String fileExtension = "." + FilenameUtils.getExtension(filePath);

int fileType = 0;

if(fileExtension.equalsIgnoreCase(".jpg") || fileExtension.equals(".jpeg"))
fileType = 1;

if(fileExtension.equals(".gif"))
fileType = 2;

if(fileExtension.equals(".zip"))
fileType = 3;

try {
srvResponse.writeBytes(httpHeaderConstructor(200, fileType));
srvResponse.close();
requestedFile.close();

} catch (Exception e) {
System.out.println("Error message: " + e.getMessage());
}

}

private static String httpHeaderConstructor(int returnCode, int typeOfFile){

String s = "HTTP/1.0";

switch (returnCode) {
case 200:
s += "200 OK";
break;

case 400:
s += "400 Bad Request";
break;

case 403:
s += "403 Forbidden";
break;

case 404:
s += "404 File not found";
break;

case 500:
s += "500 Internal server error";
break;

case 501:
s += "501 Not implemented";
break;
}

s = s + "\r\n";
s = s + "Connection: closing...\r\n";
s = s + "Server: Java HTTP Server v0.1\r\n";


switch (typeOfFile) {
case 0:
break;

case 1:
s = s + "Content-Type: image/jpeg\r\n";
break;
case 2:
s = s + "Content-Type: image/gif\r\n";
break;
case 3:
s = s + "Content-Type: application/x-zip-compressed\r\n";
break;
default:
s = s + "Content-Type: text/html\r\n";
break;
}

s = s + "\r\n";

System.out.println("The returning header is: " + s);

return s;

}
}
<小时/>

这是程序正在构建的 header :

HTTP/1.0 200 OK
Connection: close
Server: Java HTTP Server v0.1
Content-Type: image/jpeg

这些是浏览器中显示的 HTML 标记:

<html>

<head></head>
<body>
<img src="http://localhost:6565/Moon.jpg" alt="The image “http://localhost:6565/Moon.jpg” cannot be displayed because it contains errors."></img>
</body>

</html>

这就是当您尝试获取 .jpeg 图像时发生的情况。

最佳答案

首先,考虑来自 here 的示例响应 header

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
ETag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 131
Connection: close

其次,更改您的函数httpHeaderConstructor

 private static String httpHeaderConstructor(
int returnCode, int typeOfFile) {
// You should use a StringBuilder.
StringBuilder sb = new StringBuilder("HTTP/1.0 "); // <--
// Missed
// space.
switch (returnCode) {
case 200:
sb.append("200 OK");
break;
case 400:
sb.append("400 Bad Request");
break;
case 403:
sb.append("403 Forbidden");
break;
case 404:
sb.append("404 File not found");
break;
case 500:
sb.append("500 Internal server error");
break;
case 501:
sb.append("501 Not implemented");
break;
}

sb.append("\r\n");
sb.append("Connection: close\r\n"); // <-- Not closing
sb.append("Server: Java HTTP Server v0.1\r\n");

switch (typeOfFile) {
// case 0: // <-- Not a good idea.
// break;
case 1:
sb.append("Content-Type: image/jpeg\r\n");
break;
case 2:
sb.append("Content-Type: image/gif\r\n");
break;
case 3:
sb.append(
"Content-Type: application/x-zip-compressed\r\n");
break;
default:
sb.append("Content-Type: text/html\r\n");
break;
}

sb.append("\r\n");
System.out.println("The returning header is: " + sb.toString());
return sb.toString();
}

关于java - 为 Java HTTP 服务器构建 http header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com