Detect the end of an HTTP Request in Java

2019-07-19 00:51发布

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?

1条回答
狗以群分
2楼-- · 2019-07-19 01:11

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.

查看更多
登录 后发表回答