用HttpClientBuilder替换Apache DefaultHttpClient会导致“不支持http协议”异常

问题描述 投票:0回答:1

我正在尝试替换以下已弃用的(例如 Apache DefaultHttpClient、SSLSocketFactory 已弃用)代码:

public class HttpUtil {
    public static DefaultHttpClient getDefaultHttpClient(IClientConfiguration configuration,
                                                         ExternalAPILogger logger) {
        DefaultHttpClient client = new DefaultHttpClient();

        if(configuration.isIgnoreSSLCertificate()) {
            try {
                SSLContext context = SSLContext.getInstance("TLS");
                X509TrustManager trustManager = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                context.init(null, new TrustManager[]{trustManager}, null);
                SSLSocketFactory sslSocketFactory = new SSLSocketFactory(context);
                sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                ClientConnectionManager connectionManager = client.getConnectionManager();
                SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry();
                schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
                client = new DefaultHttpClient(connectionManager, client.getParams());
            } catch (NoSuchAlgorithmException e) {
                logger.log(HttpUtil.class.getName(), "TLS not available", e, ExternalAPILogger.DEBUG);
            } catch(KeyManagementException e) {
                logger.log(HttpUtil.class, "ssl context init failed", e, ExternalAPILogger.DEBUG);
            }
        }

        if(configuration.isUseProxy()) {
            HttpHost proxy = new HttpHost(configuration.getProxyHost(),
                    configuration.getProxyPort());
            ConnRouteParams.setDefaultProxy(client.getParams(), proxy);
        }

        client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);
        client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60 * 1000);

        return client;
    }
}

通过这个新代码:

    public static HttpClient getHttpClient(IClientConfiguration configuration,
                    ExternalAPILogger logger) {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        // clientBuilder.useSystemProperties();

        if (configuration.isIgnoreSSLCertificate()) {
            try {
                SSLContext context = SSLContext.getInstance("TLS");
                X509TrustManager trustManager = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                                    throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                                    throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                context.init(null, new TrustManager[] { trustManager }, null);
                // clientBuilder.setSSLContext(context);
                // clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
                SSLConnectionSocketFactory sslSocketFactory =
                                new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
                clientBuilder.setSSLSocketFactory(sslSocketFactory);

                Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("https", sslSocketFactory).build();
                HttpClientConnectionManager httpClientConnectionManager =
                                new BasicHttpClientConnectionManager(schemeRegistry);
                clientBuilder.setConnectionManager(httpClientConnectionManager);
            } catch (NoSuchAlgorithmException e) {
                logger.log(HttpUtil.class.getName(), "TLS not available", e, ExternalAPILogger.DEBUG);
            } catch (KeyManagementException e) {
                logger.log(HttpUtil.class, "ssl context init failed", e, ExternalAPILogger.DEBUG);
            }
        }

        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
        if (configuration.isUseProxy()) {
            HttpHost proxy = new HttpHost(
                            configuration.getProxyHost(),
                            configuration.getProxyPort());
            // clientBuilder
            //     .setRoutePlanner(new DefaultProxyRoutePlanner(proxy))
            //     .setProxy(proxy)
            //     .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            requestConfigBuilder.setProxy(proxy);
        }
        requestConfigBuilder
                        .setConnectTimeout(60 * 1000)
                        .setSocketTimeout(60 * 1000);
        clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

        // SocketConfig.Builder socketConfig = SocketConfig.custom();
        // socketConfig.setSoTimeout(60 * 1000);
        // clientBuilder.setDefaultSocketConfig(socketConfig.build());

        return clientBuilder.build();
    }

但是我在使用 http 代理运行代码时遇到问题。我收到以下错误消息。:

Caused by: org.apache.http.conn.UnsupportedSchemeException: http protocol is not supported

java apache-httpclient-4.x
1个回答
0
投票

尝试为“schemeRegistry”添加此内容:

*.register("http", new PlainConnectionSocketFactory())*
© www.soinside.com 2019 - 2024. All rights reserved.