Java实现HTTP服务器时如何读取POST请求的body内容
问题原因
你遇到的阻塞问题是因为HTTP/1.1默认启用长连接(Keep-Alive),客户端发送完请求后不会主动关闭TCP连接,输入流不会到达结束位置,直接调用readLine()或read()会持续等待新数据,不会返回null。
读取POST Body必须严格遵循HTTP协议规范,通过请求头中的Content-Length字段获取Body的长度,按指定长度读取内容即可。
解决方案
修改后的代码如下:
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); StringBuilder request = new StringBuilder(); String line; int contentLength = 0; // 读取请求行+请求头,同时提取Content-Length while (!(line = br.readLine()).isEmpty()) { request.append(line).append(CRLF); System.out.println(line); // 匹配Content-Length头 if (line.toLowerCase().startsWith("content-length:")) { contentLength = Integer.parseInt(line.split(":")[1].trim()); } } // 读取Body if (contentLength > 0) { char[] bodyBuf = new char[contentLength]; br.read(bodyBuf, 0, contentLength); String body = new String(bodyBuf); // 拿到body后可自行处理逻辑 System.out.println("请求Body:" + body); }
注意事项
- 如果需要支持
Transfer-Encoding: chunked分块传输的请求,需要额外按照分块格式逐块读取内容,不能直接用Content-Length读取 - 如果要兼容更复杂的HTTP场景,建议优先使用成熟的HTTP服务器框架,避免自行处理协议细节出现兼容问题
内容的提问来源于stack exchange,提问作者tweekz
相关产品推荐
相关产品推荐

