Как получить заголовки ответа из запроса CONNECT, используя apache java HttpClient 4.5? - PullRequest
1 голос
/ 07 мая 2020

Я использую прокси-сервер http для подключения к веб-сайту https через CloseableHttpClient. Запрос 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(). Заранее спасибо :)

1 Ответ

1 голос
/ 08 мая 2020

Вам понадобится собственный класс HttpClientBuilder, чтобы иметь возможность добавлять пользовательский перехватчик протокола в процессор протокола HTTP, используемый для выполнения методов CONNECT.

HttpClient 4.5 Это некрасиво, но выполнит свою работу:

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

};

HttpClient 5.0 classi c:

CloseableHttpClient httpClient = HttpClientBuilder.create()
        .replaceExecInterceptor(ChainElement.CONNECT.name(),
                new ConnectExec(
                        DefaultConnectionReuseStrategy.INSTANCE,
                        new DefaultHttpProcessor(new RequestTargetHost()),
                        DefaultAuthenticationStrategy.INSTANCE))
        .build();
...