Apache HttpClient 使用代理服务器 Proxy 的一个小坑

今天在调试一个用 HttpClient 写的 Demo 的时候遇到了一个问题:

org.apache.http.impl.execchain.RetryExec execute
INFO: I/O exception (org.apache.http.conn.UnsupportedSchemeException) caught when processing request to {tls}->http://proxyserver:port->https://servername:443: http protocol is not supported

也就是在通过 HTTP Proxy 进行 HTTPS 连接的时候,HttpClient 报了一个不支持 HTTP 协议。查了一下发现问题在于我使用 HttpClient 的方法。

由于我在使用 HttpClient 的时候是手动创建的 Registry ,而在创建的时候没有注册 HTTP 协议,导致报了上面那个错误。之前错误的代码是:

        // Create a registry of custom connection socket factories for supported
        // protocol schemes.
        Registry socketFactoryRegistry = RegistryBuilder.create()
                .register("https", sslsf)
                .build();

        // Create a connection manager with custom configuration.
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

需要修改为:

        // Create a registry of custom connection socket factories for supported
        // protocol schemes.
        Registry socketFactoryRegistry = RegistryBuilder.create()
                .register("https", sslsf)
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .build();

        // Create a connection manager with custom configuration.
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

加的这句保证了这个ConnectionSocketFactory 也可以处理 HTTP 协议,从而避免这个问题。

CC BY-NC-SA 4.0 Apache HttpClient 使用代理服务器 Proxy 的一个小坑 by 桔子小窝 is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

发表回复

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据