我正在嘗試POST一些從InputStream中獲取的數據。我希望避免必須首先將所有數據收集到一個字節數組中,而不是流式傳輸數據,以節省內存(我在發佈大約10MB的數據)。當使用Apache HttpClient發佈MultipartEntity時,ByteArrayBody可以工作,但InputStreamBody拋出NoHttpResponseException
如果我運行以下命令:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(target_url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("data", new InputStreamBody(new ByteArrayInputStream(new byte[1]),
filename));
httpPost.setEntity(entity);
httpclient.execute(httpPost);
然後我得到:
org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:712)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:517)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
[my code starts here]
不過,如果我更改上面一行,用等價ByteArrayBody更換InputStreamBody,就萬事大吉了:
entity.addPart("data", new ByteArrayBody(new byte[1], filename));
我在做什麼錯?
(並會InputStreamBody實際流中的數據,還是我浪費我的時間?)
我使用的HttpClient-4.2.1
有道理,謝謝!我想我會堅持使用'ByteArrayBody'。 – DNA 2012-07-25 14:06:25