Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 948
RandomUser Avatar asked Aug 16 '12 03:08

RandomUser


2 Answers

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();
like image 180
Tom Holmes Avatar answered Nov 04 '22 08:11

Tom Holmes


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(""));
like image 22
Vrakfall Avatar answered Nov 04 '22 07:11

Vrakfall