I am trying to use core Java to read HTTP request data from an inputstream, 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 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
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. 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. Even if not the case, you would like to prevent that in order for your server not to crash because of a NullPointerException.
To avoid that, just add the null test to your condition, like this:
while ((inputLine = in.readLine()) != null && !inputLine.equals(""));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With