Apache Commons HttpAsyncClient是否支持GZIP?

问题描述 投票:2回答:1

此问题被问到Apache Commons HttpClient,但是我正在使用async client HttpAsyncClient

内容解压缩(gzip)不能立即使用。

我尝试通过以下方式进行配置:

httpClientAsync = HttpAsyncClients.custom()
            .setMaxConnPerRoute(100)
            .setMaxConnTotal(200)
            // Enable response content encoding (gzip)
            //
            // NOTE: Does not work for some reason
            .addInterceptorLast(ResponseContentEncoding())

我从HttpClientBuilder复制而来,但不起作用。

有什么想法吗?

java apache-httpclient-4.x apache-httpasyncclient
1个回答
2
投票

使用addInterceptorLastaddInterceptorFirst无效。默认情况下,asyncHttpClient.execute()将创建一个BasicAsyncResponseConsumer。此BasicAsyncResponseConsumer会将原始ContentDecoder复制到缓冲区中,从而导致从不调用DecompressingEntity.getContent()

org.apache.http.impl.nio.client.CloseableHttpAsyncClient#execute()

    public Future<HttpResponse> execute(
            final HttpHost target, final HttpRequest request, final HttpContext context,
            final FutureCallback<HttpResponse> callback) {
        return execute(
                HttpAsyncMethods.create(target, request),
                HttpAsyncMethods.createConsumer(), // BasicAsyncResponseConsumer
                context, callback);
    }

org.apache.http.nio.protocol.BasicAsyncResponseConsumer#onContentReceived

    protected void onContentReceived(
            final ContentDecoder decoder, final IOControl ioControl) throws IOException {
        Asserts.notNull(this.buf, "Content buffer");
        this.buf.consumeContent(decoder);
    }

我的解决方案是在回调中手动调用ResponseContentEncoding.process(resp, context)以重置HttpEntity。

private static final ResponseContentEncoding responseContentEncoding = new ResponseContentEncoding();

HttpClientContext hcc = HttpClientContext.create();
asyncHttpClient.execute(bidreq, hcc, new FutureCallback<HttpResponse>() {
    @Override
    public void completed(HttpResponse result) {
        HttpEntity entity = null;
        String content = null;
        try {
            responseContentEncoding.process(result, hcc);
            entity = result.getEntity();
            if (entity != null) {
                content = EntityUtils.toString(entity, UTF_8);
                log.info(content);
            }
        } catch (Exception e) {
            log.error("error", e);
        } finally {
            EntityUtils.consumeQuietly(entity);
        }
    }

    @Override
    public void failed(Exception ex) {
        log.error("failed", ex);
    }

    @Override
    public void cancelled() { }
});
© www.soinside.com 2019 - 2024. All rights reserved.