添加 http header "User-Agent" 到 HTTP CONNECT 请求

Add http header "User-Agent" to HTTP CONNECT request

先决条件

问题

我尝试通过http4 组件调用一个https 加密站点。 位于我的服务器和互联网(目标服务器)之间的代理检查 header "User-Agent" 并在它为空时拒绝请求。

connect-Request 不包含 http header "User-Agent".

在 org.apache.http.impl.execchain.MainClientExec 方法 private boolean createTunnelToTarget(AuthState proxyAuthState, HttpClientConnection managedConn, HttpRoute route, HttpRequest request, HttpClientContext context) throws HttpException, IOException 中调用以下方法:

    BasicHttpRequest connect = new BasicHttpRequest("CONNECT", authority, request.getProtocolVersion());
    this.requestExecutor.preProcess(connect, this.proxyHttpProcessor, context);

this.requestExecutor.preProcess 添加 header "Host" 和 "Proxy-Connection" 到 HTTP CONNECT 请求,但不添加 "User-Agent".

如何将 Header "User-Agent" 添加到 HTTP CONNECT 请求?

此致,

最大

问题已在httpclient 4.4.1中解决

在 class org.apache.http.impl.client.HttpClientBuilder 中,http 处理器使用用户代理的 HttpRequestInterceptor 初始化:

    ClientExecChain execChain = createMainExec(
            requestExecCopy,
            connManagerCopy,
            reuseStrategyCopy,
            keepAliveStrategyCopy,
            new ImmutableHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)),
            targetAuthStrategyCopy,
            proxyAuthStrategyCopy,
            userTokenHandlerCopy);

解决办法是将httpclient版本从4.3.3更新到4.4.1。 在 Maven 中,我必须定义依赖关系,这样就不会选择骆驼使用的版本。