Java 在BufferedReader中处理空行

Java 在BufferedReader中处理空行,java,http-post,inputstream,bufferedreader,Java,Http Post,Inputstream,Bufferedreader,我收到一位客户的发帖请求: HTTP method: POST Host: 127.0.0.1:52400 Connection: keep-alive Content-Length: 18 Pragma: no-cache Cache-Control: no-cache Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Origin: null User-Agent: Mozil

我收到一位客户的发帖请求:

HTTP method: POST
Host: 127.0.0.1:52400
Connection: keep-alive
Content-Length: 18
Pragma: no-cache
Cache-Control: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip,deflate
Accept-Language: da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2

fname=foof&pw=bar
我运行了一个小型且非常简单的Java Web服务器,从InputStream获取此请求。 在BufferedReader中,我将数据设置为一个字符串,其中包含请求,如下所示:

for (String line; (line = in.readLine()) != null; ) {
    if (line.isEmpty()) break;
    header += line + "\n";
}
当我将标题打印到控制台时,我得到以下信息:

POST / HTTP/1.1
Host: 127.0.0.1:52400
Connection: keep-alive
Content-Length: 18
Pragma: no-cache
Cache-Control: no-cache
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: null
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip,deflate
Accept-Language: da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2
忽略POST参数


我猜这个问题是由于POST请求中的空行引起的。

如何确保BufferedReader将请求读取到底,而不是在空行处停止,尽管在BufferedReader到达请求末尾时停止

请忽略本例中缺乏安全性的问题-我现在只需要将POST请求转换为纯字符串表示

在此方面的任何帮助我都很感激,谢谢!
Jesper.

问题是因为在
for
循环中有一个
中断。当您到达空白行时,它会碰到<代码>中断<代码>并退出循环,此后不添加任何行。相反,您应该使用以下选项:

for (String line; (line = in.readLine()) != null; ) {
    if (line.isEmpty()) continue;
    header += line + "\n";
}
通过使用
continue
而不是
break
,循环将继续进行下一次迭代,并且可以添加其余的行


可以找到更多的信息

“我猜问题是由于POST请求中的空行发生的。”-您通过单元测试或示例请求验证了删除空白行吗?可能相关:@ SUMJEJE,我刚刚更新了我的问题,关于您的代理不认为它的空行相关问题。并且readLine()不会返回不带尾随的字符串
\r\n
。你能把代码贴出来吗?你是如何显示行的?或者请把完整的代码贴出来。