我正在使用 Apache HttpClient 4.3.3 API。
HttpResponse response = client.execute(request);
某些请求会在响应正文中发送响应。有些请求用于从服务器下载文件,这意味着客户端可以将此内容写入文件。
如何使用HttpResponse区分以上两类请求的响应。
HttpEntity entity = response.getEntity();
我认为“entity.isStreaming()”适合我的用例。但它在所有请求中都为我返回 true。
最佳答案
我认为在正常使用中,流式传输与非流式传输的差异封装在您在下面看到的“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;
}
关于java - 如何知道HttpResponse内容是字符串还是流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23389322/