1
我試圖解析HTTP請求,使用apache httpcore components並希望獲取請求的正文。它看起來像默認DefaultHttpRequestParser
不解析其輸入流中的主體/實體。有沒有一個班會這樣做?HttpRequest返回null實體,無法提取服務器上的主體
不幸的是我不能使用整個堆棧,並且需要直接從這個輸入流中提取請求。
我的解析代碼如下。看看其他一些答案,似乎請求的主體應該作爲一個實體提供。但是,每次我嘗試查看實體時都是空的。
調試我看到緩衝區已經讀取但沒有使用正文,並且DefaultHttpRequestParser
似乎只是讀取標題。有沒有解析我應該用來解析整個輸入?
InputStream is = socket.getInputStream();
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
SessionInputBufferImpl buf = new SessionInputBufferImpl(metrics, 2048);
buf.bind(is);
DefaultHttpRequestParser reqParser = new DefaultHttpRequestParser(buf);
HttpRequest req = reqParser.parse();
if (req instanceof HttpEntityEnclosingRequest) {
entity = ((HttpEntityEnclosingRequest)query).getEntity();
//... entity is always null
如果我讀的輸入流我結束了:
POST/HTTP/1.1
User-Agent: curl/Q.XX.0 (linux-gnu) libcurl/Q.XX.0 OpenSSL/X.Y.Z zlib/A.B.C.D libidn/E.FF librtmp/G.H
Host: localhost:8088
Accept: */*
Content-Length: 333
Content-Type: multipart/form-data; boundary=----------------------------39203c7982df
------------------------------39203c7982df
Content-Disposition: form-data; name="fileupload"; filename="grun.sh"
Content-Type: application/octet-stream
#!/bin/bash -x
java -classpath lib/antlr-4.4-complete.jar:build/classes org.antlr.v4.runtime.misc.TestRig Typegroup "AHI" -tree
------------------------------39203c7982df--
[更新]奧列格有一個很好的答案,但我的身體與請求或者我現在聯想做 需要通過兩件事情,身體和流?我會調查
我得到以下工作,但它在最新版本中已棄用。
...
HttpEntityEnclosingRequest ereq = (HttpEntityEnclosingRequest) req;
@SuppressWarnings("deprecation")
EntityDeserializer ed =
new EntityDeserializer(new LaxContentLengthStrategy());
@SuppressWarnings("deprecation")//ack!
HttpEntity ent = ed.deserialize(buf, req);
ereq.setEntity(ent);
return ereq;
結合Oleg的溶液與我結束了以上:
HttpEntityEnclosingRequest ereq = (HttpEntityEnclosingRequest) req;
ContentLengthStrategy contentLengthStrategy =
StrictContentLengthStrategy.INSTANCE;
long len = contentLengthStrategy.determineLength(req);
InputStream contentStream = null;
if (len == ContentLengthStrategy.CHUNKED) {
contentStream = new ChunkedInputStream(buf);
} else if (len == ContentLengthStrategy.IDENTITY) {
contentStream = new IdentityInputStream(buf);
} else {
contentStream = new ContentLengthInputStream(buf, len);
}
BasicHttpEntity ent = new BasicHttpEntity();
ent.setContent(contentStream);
ereq.setEntity(ent);
return ereq;