从 Java 套接字 InputStream 读取请求内容,总是在 header 之后挂起

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11980255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:09:07  来源:igfitidea点击:

Reading request content from Java socket InputStream, always hangs after header

java

提问by Zugdud

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. 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

我收到的标头很好,但是客户端永远挂起,因为服务器永远找不到请求的“EOF”。我该如何处理?我已经看到这个问题问了很多,大多数解决方案都涉及上述内容,但是它对我不起作用。我已经尝试使用 curl 和 Web 浏览器作为客户端,只是发送一个 get 请求

Thanks for any ideas

感谢您的任何想法

回答by Tom Holmes

An HTTP request ends with a blank line (optionally followed by request data such as form data or a file upload), not an EOF. You want something like this:

HTTP 请求以空行结束(可选地后跟请求数据,例如表单数据或文件上传),而不是 EOF。你想要这样的东西:

BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while (!(inputLine = in.readLine()).equals(""))
    System.out.println(inputLine);
in.close();

回答by Vrakfall

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. Even if not the case, you would like to prevent that in order for your server not to crash because of a NullPointerException.

除了上面的答案(因为我还不能发表评论),我想补充一些像 Opera 这样的浏览器(我猜是它做了什么,或者是我的 ssl 设置,我不知道) 发送 EOF。即使不是这种情况,您也希望防止这种情况发生,以便您的服务器不会因为 NullPointerException 而崩溃。

To avoid that, just add the null test to your condition, like this:

为避免这种情况,只需将空测试添加到您的条件中,如下所示:

while ((inputLine = in.readLine()) != null && !inputLine.equals(""));