简体   繁体   中英

Android : HTTPS urls are not working in Okhttp3

I am using Okhttp3 in my android application to download files. I am having problem with https urls.

I have two URLS

    String url1 = "https://cbsenet.nic.in/cbsenet/PDFDEC2014/Paper%20III/D-01-3.pdf";
    String url2 = "https://www.ugcnetonline.in/question_papers/June2014_paper-II/J-02-14-II.pdf";

url2 is working fine while for url1 I am getting exception

Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I have created a sample java program to demonstrate the problem

public static void main(String[] args) throws IOException {

    String url1 = "https://cbsenet.nic.in/cbsenet/PDFDEC2014/Paper%20III/D-01-3.pdf";
    String url2 = "https://www.ugcnetonline.in/question_papers/June2014_paper-II/J-02-14-II.pdf";

    Request request = new Request.Builder()
            .url(url1)
            .build();

    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();
    System.out.println(response.body().string());
}

This is my solution, It works

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

                    @SuppressLint("TrustAllX509TrustManager")
                    @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();


        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @SuppressLint("BadHostnameVerifier")
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    builder.connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true);
    return builder.build();
}

Since at last, you choose to trust all cers for your url1 , then how could you make your url2 worked before?

BR, Xiangbin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM