java - 如何知道HttpResponse内容是字符串还是流

标签 java httpclient apache-httpclient-4.x apache-httpcomponents

我正在使用 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/

相关文章:

java - 无法解析类型 org.eclipse.core.runtime.IConfigurationElement

java - 一致性和容器管理的事务

java - 你如何在 khttp 中发送原始 byteArray 作为 post 请求的主体?

android - 不能从静态上下文中引用非静态方法

java - 如何在 Apache HttpClient 4.3+ 中设置默认 HttpHost 目标?

android - Android 4.4 上的 Apache HttpClient 4.3

java - Android 应用程序已停止并出现 NoClassDefFoundError

java - 三元运算符导致的意外类型

c# - HttpClient HttpRequestException

java - Tomcat 实例中 webapps 之间的连接重置