[英]Reading request content from Java socket InputStream, always hangs after header
I am trying to use core Java to read HTTP request data from an inputstream, using the following code: 我正在尝试使用核心Java从输入流中读取HTTP请求数据,使用以下代码:
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
I receive the header fine, but then the client just hangs forever because the server never finds "EOF" of the request. 我收到标题很好,但客户端只是永远挂起,因为服务器永远不会找到请求的“EOF”。 How do I handle this?
我该如何处理? I've seen this question asked quite a bit, and most solutions involve something like the above, however it's not working for me.
我已经看到了这个问题,并且大多数解决方案都涉及到类似上面的内容,但是它对我不起作用。 I've tried using both curl and a web browser as the client, just sending a get request
我尝试使用curl和Web浏览器作为客户端,只是发送一个get请求
Thanks for any ideas 谢谢你的任何想法
An HTTP request ends with a blank line (optionally followed by request data such as form data or a file upload), not an EOF. HTTP请求以空行结束(可选地后跟请求数据,如表单数据或文件上载),而不是EOF。 You want something like this:
你想要这样的东西:
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while (!(inputLine = in.readLine()).equals(""))
System.out.println(inputLine);
in.close();
In addition to the answer above (as I am not able to post comments yet), I'd like to add that some browsers like Opera (I guess it was what did it, or it was my ssl setup, I don't know) send an EOF. 除了上面的答案(因为我还没有发表评论),我想补充一些浏览器,比如Opera(我猜它是做了什么,或者是我的ssl设置,我不知道)发送EOF。 Even if not the case, you would like to prevent that in order for your server not to crash because of a NullPointerException.
即使不是这种情况,您也希望防止这种情况,以免您的服务器因NullPointerException而崩溃。
To avoid that, just add the null test to your condition, like this: 为避免这种情况,只需将null测试添加到您的条件中,如下所示:
while ((inputLine = in.readLine()) != null && !inputLine.equals(""));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.