在 Java 中“解析 HTTP 报文”通常有几种层次,取决于你是自己处理原始字节/字符串,还是使用现成库。下面按常见场景给你讲清楚。
HTTP 报文基本结构:
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: curl/7.0
Accept: */*
body(可选)
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 11
Hello World
public class HttpParser {
public static void main(String[] args) {
String request = """
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Java
""";
String[] lines = request.split("\r\n");
// 请求行
String[] requestLine = lines[0].split(" ");
String method = requestLine[0];
String path = requestLine[1];
String version = requestLine[2];
// 请求头
for (int i = 1; i < lines.length; i++) {
if (lines[i].isEmpty()) break;
String[] header = lines[i].split(": ");
System.out.println(header[0] + " => " + header[1]);
}
}
}
⚠️ 实际生产中不要自己写完整 HTTP 解析器,容易出错。
HttpURLConnection conn =
(HttpURLConnection) new URL("http://example.com").openConnection();
int code = conn.getResponseCode();
String contentType = conn.getContentType();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
✅ Java 已经帮你解析:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.build();
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.headers().map());
System.out.println(response.body());
✅ 自动解析 HTTP 报文
✅ 支持 HTTP/2
✅ 现代写法
如果你是写 Web 服务器 / Netty / 网关,需要解析客户端发来的 HTTP:
ServerSocket server = new ServerSocket(8080);
Socket socket = server.accept();
BufferedReader in =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while (!(line = in.readLine()).isEmpty()) {
System.out.println(line);
}
⚠️ 仅适合学习,不建议生产使用
| 需求 | 推荐方式 |
|---|---|
| 解析 URL 参数 | URI, HttpServletRequest |
| 解析 JSON Body | Jackson / Gson |
| 解析 Form 表单 | Spring @RequestParam |
| 解析 Header | getHeader() |
学习原理 → 手动解析
写业务 → 用框架
写服务器 → Netty / Spring
如果你能告诉我:
我可以给你更精确的代码示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。