Search code examples
javaapache-httpclient-4.xapache-commonsapache-commons-httpclient

Apache HttpClient: how to send headers along with CONNECT request


I need to connect to a proxy that reads headers in CONNECT requests. I mean specifically the headers that are passed along with CONNECT, before switching to en HTTPS-encrypted stream.

Is that possible with HttpClient? Its default behaviour seems to be to push all headers through the encrypted stream.


Solution

  • I am not sure you should be doing this (I personally do not see a valid reason for adding custom headers to CONNECT requests) but this is how this could be done with HttpClient 4.3 or newer

    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();