2012-07-24 77 views
2

我正在嘗試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

回答

2

沒有什麼錯,你在做什麼。問題很可能是因爲當使用ByteArrayBody時,HttpClient能夠計算總請求內容長度並使用Content-Length描述消息,而在使用InputStreamBody時,HttpClient必須使用內容分塊(使用Transfer-Encoding標頭)。我懷疑服務器端腳本根本無法處理沒有Content-Length標頭的請求。

+0

有道理,謝謝!我想我會堅持使用'ByteArrayBody'。 – DNA 2012-07-25 14:06:25

相關問題