Home > Mobile >  Get body of POST request [Java]
Get body of POST request [Java]

Time:12-01

I'm trying to write a simple HTTP server but can't figure out how to read the body segment of a POST-request. I'm having trouble reading beyond the empty line after the headers.

Here's what I do:

    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
    StringBuilder request = new StringBuilder();
    String line;
    while(!(line = br.readLine()).isEmpty()) {
        request.append(line).append(CRLF);
        System.out.println(line);
    }
    
    // read body ?

So this basically loads the Request and headers in a String. But I can't figure out how to skip that one line that separates the headers from the body.

I've tried readLine() != null or to manually read two more lines after the loop terminates, but that results in a loop.

CodePudding user response:

Try parsing the content-length header to get the number of bytes. After the blank line you'll want to read exactly that many bytes. Using readLine() won't work because the body isn't terminated by a CRLF.

  • Related