【发布时间】:2016-03-12 14:45:07
【问题描述】:
我在尝试提取给定的主体时遇到了一个奇怪的问题 HTTP 发布请求。
如果我尝试只提取标题,它工作正常。当我尝试提取主体时,方法会阻塞(即使流中仍有数据)。
这是我的代码:
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() 的原因是 body 不以 \n 结尾)。
我尝试过以各种方式对其进行调试,但我一无所获。有人可以帮忙吗?
【问题讨论】:
-
现在假设 bodyLength 的值大于 0。在使用空字符串“”而不是 /r/n 时仅提取标题时我没有遇到任何问题。在这种情况下,当循环在读取空行(该部分有效)后结束时,从流中读取 x 个字符(x = content-length)应该没有问题,但它在激活时只是阻塞。
标签: java http post request server