【问题标题】:How to know HttpResponse content is string or stream如何知道 HttpResponse 内容是字符串还是流
【发布时间】:2014-04-30 13:23:41
【问题描述】:

我正在使用 Apache HttpClient 4.3.3 API。

HttpResponse response = client.execute(request);

一些请求将在响应正文中发送响应。一些请求用于从服务器下载文件,这意味着客户端可以将此内容写入文件。

如何使用HttpResponse区分以上两种请求的响应。

HttpEntity entity = response.getEntity();

我认为“entity.isStreaming()”适用于我的用例。但它在所有请求中对我来说都是真实的。

【问题讨论】:

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


    【解决方案1】:

    我认为在正常使用中,流式与非流式的区别封装在您在下面看到的“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;
    }
    

    【讨论】:

      【解决方案2】:

      响应实体总是流式传输(除非使用启用缓存HttpClient)。请求实体可以是流式(由不可重复的InputStream 支持)或非流式(由字符串、字节数组、文件或类似的内存或文件系统绑定对象支持)

      【讨论】:

        猜你喜欢
        • 2019-09-02
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        • 1970-01-01
        • 2012-09-12
        • 1970-01-01
        • 2013-04-14
        • 2012-02-04
        相关资源
        最近更新 更多