Reading request contents from Java InputStream socket always hangs after header

I am trying to use basic Java to read HTTP request data from an input stream using the following code:

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

I get the header perfectly, but then the client just hangs forever, because the server never finds an "EOF" request. How can I handle this? I saw that this question was asked quite a lot, and most of the solutions are related to something like the above, however this does not work for me. I tried using both curl and the web browser as a client, just by sending a request for

Thanks for any ideas.

+6
source share
2 answers

An HTTP request ends with an empty string (optionally followed by request data such as form data or file upload), not 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(); 
+10
source

In addition to the answer above (since I still can’t leave comments), I would like to add that some browsers like Opera (I think it was what it was, or it was my ssl setting, I don’t know ) send EOF. Even if this is not the case, you would like to prevent this from happening so that your server does not crash due to a NullPointerException.

To avoid this, simply add a null test to your state, for example:

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

Source: https://habr.com/ru/post/923006/


All Articles