javax.net.ssl.SSLPeerUnverifiedException从Skyscanner API检索会话密钥时出错 - Android

时间:2016-09-12 08:10:26

标签: android retrofit2 okhttp3

我一直致力于 Sky scanner API 来检索机票中的航班票价和其他详细信息。

我正在使用 Retrofit2 进行网络通话。问题是在检索会话密钥时出错

错误

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;
}

在android

中引用了SSLPeerUnverifiedException的SO链接

Link1 Link2

1 个答案:

答案 0 :(得分:0)

我在 BNK 评论

的帮助下解决了这个问题
  1. 在OkhttpClient对象中添加 HostnameVerifier()
  2. 检查主机名,然后在 hv.verify(hostname, session);
  3. 中添加主机名

    固定代码供参考

     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();
        }