jd.
jd.

Reputation: 10958

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.

Upvotes: 1

Views: 1503

Answers (1)

ok2c
ok2c

Reputation: 27558

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

Upvotes: 3

Related Questions