Fabiotk Fabiotk - 1 year ago 61
Java Question

Java Socket not receiving body of http request

I'm trying to read a HTTP request using only

classes in Java. The problem is that I can't reach the body part of the request. The Buffered reader is giving me only the request line and the headers. Here is part of the code:

bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String comando = "";
while((msgDoSocket = bufferedReader.readLine()) != null){
try {
comando += msgDoSocket + " ";
} catch (Exception ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);

Here is a WireShark capture showing that the POST body is being sent. My program is running on port 15000 and the data is just a string "teste12345". I'm using the app POSTMAN from google chrome to send the requests.

enter image description here

I'm having exactly the same problem described in this thread but the solutions proposed there didn't work. The request still getting up to the last header and no more. Thanks in advance.

Edit: Problem Solved!
Following suggestion proposed on the answer, I changed the reading to:

reader = new DataInputStream(socket.getInputStream());

String comando = "";
while( (dt = reader.readByte()) >= 0){
comando += dt;
//... do the rest of the stuff

Reading it as binary made it possible to reach the
part of the request.

Answer Source

I'm far from being a Java guru, but I bet that readLine only returns with results when it found a sequence of \r\n. since your body is not terminated with \r\n the method readLine never returns. try to manually add that character sequence to your body and see what happens, or alternatively, use the raw InputStreamReader to read the body as byte array.

never the less, you can't expect any http body to actually be a string. it can also be a binary sequence which knows nothing about \r\n.