gpt4 book ai didi

java - 从 HTTP post 请求中提取正文

转载 作者:行者123 更新时间:2023-12-01 10:46:23 29 4
gpt4 key购买 nike

当我试图提取给定的主体时,我遇到了一个奇怪的问题HTTP POST 请求。

如果我尝试仅提取 header ,则效果很好。当我尝试提取正文时,该方法会阻塞(即使流中仍然有数据)。

这是我的代码:

private void extractHeader() throws Exception {
StringBuffer buffer = new StringBuffer();
InputStreamReader reader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(reader);

boolean extractBody = false;
int bodyLength = 0;
String line;

while (!(line = bufferedReader.readLine()).equals("")) {
buffer.append(line + "");
if (line.startsWith("POST")) {
extractBody = true;
}
if (line.startsWith("Content-Length:")) {
bodyLength = Integer.valueOf(line.substring(line.indexOf(' ') + 1, line.length()));
}
}
requestHeader = buffer.toString();

if (extractBody) {
char[] body = new char[bodyLength];
reader.read(body, 0, bodyLength);
requestBody = new String(body);
}
}

这是请求请求:

POST /params_info.html HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/index.html
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 31

firstname=Mickey&lastname=Mouse

据我了解,循环将一直进行,直到看到空字符串然后停下来。在此阶段,阅读器可以读取“Content-Length”字节数。所以阅读正文并完成应该没有问题。相反,它会阻塞“reader.read(body, 0, bodyLength);”行(我不使用 readLine() 的原因是因为正文不以\n 结尾)。

我尝试过以各种方式调试它,但一无所获。有人可以帮忙解决这个问题吗?

最佳答案

您正在使用 bufferedReader 读取 header :

while (!(line = bufferedReader.readLine()).equals("")) {

但使用 reader 读取正文,该正文没有可用数据,因为该数据已由 bufferedReader 读取并缓冲:

    reader.read(body, 0, bodyLength);

将该行更改为

    bufferedReader.read(body, 0, bodyLength);

关于java - 从 HTTP post 请求中提取正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143039/

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