views:

870

answers:

2

I have written a code to send a HTTP request through a socket in java. Now I want to get the HTTP response that was sent by the server to which I sent HTTP request.

A: 

As Jon said, read the HTTP spec. However Internet protocols are generally line oriented, so you can read the response a line a time. The first line will be the response. Following this will be the headers, one per line (unless there's a continuation). If there's a body one of the headers will the content-type, this will tell you what the content is. If you want to read the content you will need to understand the different ways the content can be sent. There may be a content length header (or not) or the content maybe chunked (can't remember the header off the top of my head). And of course the content may be binary rather than text.

Kevin Jones
+2  A: 

It's not totally clear what you're asking for. Assuming you've written the request to the socket, the next thing you'll want to do is:

  • Call shutdownOutput() on the socket to tell the server that the request is done (not necessary if you've sent the content length)
  • Read the response from the socket's input stream, parsing according to the HTTP spec.

This is a bunch of work, so I'd suggest that rather than rolling your own HTTP request logic, use URLConnection which is built-in to Java and includes methods for retrieving the content of a response as well as any headers set by the server.

Dave Ray
+1 for "don't do this yourself." (You don't need to shut down the output if you've sent a content length of course.) There are other libraries available too. Ironically the OP was asking about them yesterday, so I'm not sure why they're now writing the request directly to the socket...
Jon Skeet
Definitely. I've done it once myself in C++ and it's definitely not fun. Not rocket science, but not fun either.
Dave Ray