我正在尝试POST一些从InputStream中获取的数据。我希望避免首先将所有数据收集到一个字节数组中,而是流式传输数据,以节省内存(我正在发布大约10MB的数据)。
如果我运行以下内容:
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]
但是,如果我更改上面的一行,将InputStreamBody替换为等效的ByteArrayBody,那么一切都很好:
entity.addPart("data", new ByteArrayBody(new byte[1], filename));
我做错了什么?
(并且InputStreamBody会实际传输数据,还是我在浪费时间?)
我正在使用HttpClient-4.2.1
答案 0 :(得分:2)
你在做什么没有错。问题可能是当使用ByteArrayBody
时HttpClient能够计算总请求内容长度并使用Content-Length
描述消息,而在使用InputStreamBody
时HttpClient必须求助于内容分块(使用Transfer-Encoding
标题)。我怀疑服务器端脚本无法处理没有Content-Length
标头的请求。