2

Im trying to design a Java proxy program, but my java program has issues reading an entire HTTP request.

I used the InputStream object isObj to try to obtain data:

isObj.read(byteBuff)

But this often results in the data not getting read completely. i.e in case of a POST request, sometimes, the HTTP headers alone are read while the POST data is not read. So, I tried to use the below to read the data fully.

ByteArrayOutputStream baos=new ByteArrayOutputStream();
while((len=isObj.read(tempBuff))>0){
    baos.write(tempBuff,0,len);
}
byte[] byteBuff=baos.toByteArray();

However, this method also blocked at the isObj.read(tempBuff) function.

Tried another method using the DataInputStream like:

DataInputStream dis=new DataInputStream(isObj);
byte[] byteBuff=new byte[8196];
dis.readFully(byteBuff);

This also blocked at the readFully() function.

I read through and came across this

Detect end of HTTP request body

which indicates that the reason is that there is no way we can identify when the data will get over(unless it is for a response). And it asks us to use the Content-Length header to detect the final length. Is this absolutely the only way to read HTTP Requests? Or is there any other library which does this automatically?

Community
  • 1
  • 1
Mkl Rjv
  • 6,815
  • 5
  • 29
  • 47
  • 1
    Mandatory mention of the actual specifications: http://tools.ietf.org/html/rfc2616#section-4.3 – Gimby Jun 24 '14 at 10:54

1 Answers1

5

You can use Apache's HttpComponents for this. The HttpCore library offers a DefaultHttpRequestParser which returns a HttpRequest instance with methods to get headers and fields from the request.

user2610529
  • 491
  • 3
  • 10
  • 1
    Its a good suggestion, although HttpClient specifically isn't really relevant to this question. Its about receiving a request, not sending one ;) – Gimby Jun 24 '14 at 10:56
  • I'm trying to go through HttpComponents and it usually deals with the client side and not what to do at a server side. As @Gimby mentioned is there anything which can let me handle receiving a request. – Mkl Rjv Jun 24 '14 at 11:14
  • You actually can parse HTTP Requests with it, as shown under section 3.1.3 in http://hc.apache.org/httpcomponents-core-ga/tutorial/html/advanced.html – user2610529 Jun 24 '14 at 11:25
  • You should update your answer with relevant information. – Gimby Jun 24 '14 at 11:34