Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffered Reader HTTP POST

Looking for a bit of help, I have currently written a HTTP server. It currently handles GET requests fine. However, whilst using POST the buffered reader seems to hang. When the request is stopped the rest of the input stream is read via the buffered reader. I have found a few things on google. I have tried changing the CRLF and the protocol version from 1.1 to 1.0 (browsers automatically make requests as 1.1) Any ideas or help would be appreciated. Thanks

like image 603
Hugh Avatar asked Mar 30 '26 14:03

Hugh


2 Answers

I agree with Hans that you should use a standard and well-tested library to do this. However, if you are writing a server to learn about HTTP, here's some info on doing what you want to do.

You really can't use a BufferedReader because it buffers the input and might read too many bytes from the socket. That's why your code is hanging, the BufferedReader is trying to read more bytes than are available on the socket (since the POST data doesn't have an end of line), and it is waiting for more bytes (which will never be available).

The process to simply parse a POST request is to use the InputStream directly

  • For each line in the header read a byte at a time until you get a '\r' and then a '\n'

  • Look for a line that starts with "Content-Length: ", extract the number at the end of that line.

  • When you get a header line that is empty, you're done with headers.

  • Now read exactly the # of bytes that came from the Content-Length header.

Now you can write your response.

like image 152
karoberts Avatar answered Apr 02 '26 03:04

karoberts


Wouldn't write my own implementation. Look at the following existing components, if you want:

  • a HTTP client: Apache HttpClient
  • a HTTP server implementation: Apache HttpComponents core (as mentioned by Bombe)
like image 34
Hans Doggen Avatar answered Apr 02 '26 04:04

Hans Doggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!