我正在使用Apache HttpClient 4.3.3 API。
HttpResponse response = client.execute(request);
有些请求会在响应正文中发送响应。一些请求用于从服务器下载文件,这意味着客户端可以将此内容写入文件。
如何使用HttpResponse区分上述两类请求的响应。
HttpEntity entity = response.getEntity();
我认为“ entity.isStreaming()”适用于我的用例。但是在所有请求中它都会回归真实。
答案 0 :(得分:0)
我认为在正常使用中,流v非流的差异被封装在下面看到的“entityutils.entity.consume”中。代码来自POST的使用模式中的“CloseableHttpClient”。
CloseableHttpClient...
public <T> T execute(final HttpHost target, final HttpRequest request,
final ResponseHandler<? extends T> responseHandler, final HttpContext context)
throws IOException, ClientProtocolException {
Args.notNull(responseHandler, "Response handler");
final HttpResponse response = execute(target, request, context);
final T result;
try {
result = responseHandler.handleResponse(response);
} catch (final Exception t) {
final HttpEntity entity = response.getEntity();
try {
EntityUtils.consume(entity);
} catch (final Exception t2) {
// Log this exception. The original exception is more
// important and will be thrown to the caller.
this.log.warn("Error consuming content after an exception.", t2);
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {
throw (IOException) t;
}
throw new UndeclaredThrowableException(t);
}
// Handling the response was successful. Ensure that the content has
// been fully consumed.
final HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
return result;
}
答案 1 :(得分:0)
响应实体始终是流式传输(除非使用缓存启用HttpClient
)。请求实体可以是流式传输(由不可重复的InputStream
支持)或非流式传输(由String,字节数组,文件或类似的内存或文件系统绑定对象支持)