Apache HttpClient:如何与CONNECT请求一起发送标头

时间:2015-07-01 09:09:01

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

我需要连接到一个读取CONNECT请求中的标头的代理。我指的是在切换到HTTPS加密流之前,与CONNECT一起传递的标头。

HttpClient可以实现吗?它的默认行为似乎是通过加密流推送所有标头。

1 个答案:

答案 0 :(得分:2)

我不确定你应该这样做(我个人认为没有向CONNECT请求添加自定义标头的正当理由)但是这可以通过HttpClient 4.3或更新版本来完成

class MyHttpClientBuilder extends HttpClientBuilder {

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

        final HttpProcessor myProxyHttpProcessor = new ImmutableHttpProcessor(new RequestTargetHost(), new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                request.addHeader("Hello", "Mom says hi");
            }
        });

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

HttpClientBuilder httpClientBuilder = new MyHttpClientBuilder();
CloseableHttpClient client = MyHttpClientBuilder.build();