检测Java中HTTP请求的结束 [英] Detect the end of an HTTP Request in Java
问题描述
我试图设计一个Java代理程序,但是我的java程序在读取整个HTTP请求时遇到了问题。
Im trying to design a Java proxy program, but my java program has issues reading an entire HTTP request.
我使用了 InputStream
object isObj
尝试获取数据:
I used the InputStream
object isObj
to try to obtain data:
isObj.read(byteBuff)
但这通常会导致数据无法完全读取。即,在POST请求的情况下,有时,只读取HTTP标头,而不读取POST数据。所以,我尝试使用下面的内容来完全读取数据。
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();
但是,此方法也在 isObj.read(tempBuff)<阻止
function。
However, this method also blocked at the isObj.read(tempBuff)
function.
尝试使用DataInputStream的另一种方法,如:
Tried another method using the DataInputStream like:
DataInputStream dis=new DataInputStream(isObj);
byte[] byteBuff=new byte[8196];
dis.readFully(byteBuff);
这也被阻止在 readFully()
函数。
我通读并遇到了这个
表示原因是我们无法确定何时数据将被解决(除非是为了响应)。它要求我们使用Content-Length标头来检测最终长度。这绝对是读取HTTP请求的唯一方法吗?或者是否有其他库自动执行此操作?
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?
推荐答案
您可以使用 Apache的HttpComponents 。 HttpCore库提供 DefaultHttpRequestParser 返回 HttpRequest 实例,包含从请求中获取标题和字段的方法。
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.
这篇关于检测Java中HTTP请求的结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!