如何使用apache java HttpClient 4.5从CONNECT请求中检索响应标头?

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

我使用http代理通过CloseableHttpClient连接到https网站。首先发送CONNECT请求,因为它必须进行隧道连接。将发送响应头,我需要检索它们。结果将存储在变量中,以后使用。

在HttpClient 4.2上,我可以使用HttpResponseInterceptor实现它:

final DefaultHttpClient httpClient = new DefaultHttpClient();
//configure proxy


httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
    public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
        final Header[] headers = httpResponse.getAllHeaders();

        //store headers
    }
});

但是当我使用HttpClient 4.5时,永远不会在CONNECT请求上调用我的响应拦截器。它直接在GET或POST请求上跳转:

 final CloseableHttpClient httpClient = HttpClients.custom()
                .setProxy(new HttpHost(proxyHost, proxyPort, "http"))
                .addInterceptorFirst(new HttpResponseInterceptor() {
                    public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
                        final Header[] headers = httpResponse.getAllHeaders();

                        //store headers
                    }
                }).build();

方法setInterceptorLast()setHttpProcessor()的结果相同。在此先感谢:)

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

您将需要一个自定义HttpClientBuilder类,以便能够向用于执行CONNECT方法的HTTP协议处理器添加自定义协议拦截器。它虽然不漂亮,但可以完成工作。

HttpClientBuilder builder = new HttpClientBuilder() {

    @Override
    protected ClientExecChain createMainExec(
            HttpRequestExecutor requestExec,
            HttpClientConnectionManager connManager,
            ConnectionReuseStrategy reuseStrategy,
            ConnectionKeepAliveStrategy keepAliveStrategy,
            HttpProcessor proxyHttpProcessor,
            AuthenticationStrategy targetAuthStrategy,
            AuthenticationStrategy proxyAuthStrategy,
            UserTokenHandler userTokenHandler) {

        final ImmutableHttpProcessor myProxyHttpProcessor = new ImmutableHttpProcessor(
                Arrays.asList(new RequestTargetHost()),
                Arrays.asList(new HttpResponseInterceptor() {

                    @Override
                    public void process(
                            HttpResponse response,
                            HttpContext context) throws HttpException, IOException {

                    }
                })
        );

        return super.createMainExec(requestExec, connManager, reuseStrategy, keepAliveStrategy,
                myProxyHttpProcessor, targetAuthStrategy, proxyAuthStrategy, userTokenHandler);
    }

};
© www.soinside.com 2019 - 2024. All rights reserved.