javax.net.ssl.SSLPeerUnverifiedException Error in

2019-09-12 14:59发布

问题:

I have been working on Sky scanner API to retrieve the flight fares and other details in android.

I'm using the Retrofit2 for network calls. The problem is getting error in retrieving the Session key

Error

javax.net.ssl.SSLPeerUnverifiedException: Hostname partners.api.skyscanner.net not verified:certificate: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=DN:CN=api.skyscanner.net,OU=Infrastructure,O=Skyscanner Ltd,L=London,ST=London,C=GB

APIClient

    public static Retrofit getRetrofit() {
    if (retrofit2 == null) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("partners.api.skyscanner.net", session);
            }
        }).build();

        retrofit2 = new Retrofit.Builder()
                .baseUrl(SKY_BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit2;
}

Referred SO links of SSLPeerUnverifiedException in android

Link1 Link2

回答1:

I fixed the issue with help of BNK Comments

  1. Add HostnameVerifier() in the OkhttpClient object
  2. Check the hostname before adding it in hv.verify(hostname, session);

Fixed Code for reference

 if (retrofit2 == null) {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("api.skyscanner.net", session);
            }
        }).build();

        retrofit2 = new Retrofit.Builder()
                .baseUrl(SKY_BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }