HttpClient 中的 SSL

SSL in HttpClient

我正在使用 HttpClient 的 apache 通用版本 api (Common-HttpClient),其实现似乎很简单。例如,指定代理很容易,读取网页内容(http或https)没有区别

如果我将 HttpClient 版本升级到 4.5.x,我发现很难实现相同的要求。我基本上想在代码中做事 example

我的问题是为什么在 HttpClient 4.5.x 的情况下我们需要 SSL/KeyStore?我需要做什么才能生成新的密钥库以使其正常工作?

First if you are consuming service you need to ask or download ssl certificate from server, Generated certificate will not work.
After that in you https call you need to pass this certificate.

It is not recommended but you can also bypass ssl by following code snippet. Benefit of that is if in future certificate will change you don't need to change this in your client application.

private static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
//            builder.sslSocketFactory(getSSLConfig(MyApplication.getAppContext()).getSocketFactory()); //commented to check ssl with certificate
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

My question is why do we need SSL/KeyStore in this case of HttpClient 4.5.x? what do i need to do to generate a new keystore to make it work?

为了您自己,您应该知道您的应用程序在建立安全出站连接时应该使用什么信任/密钥material。不需要为了使 SSL 工作而生成新的密钥库。可以简单地使用 Java 运行时附带的信任 material。