我在OkHttp 3.3.1中收到以下异常

javax.net.ssl.SSLPeerUnverifiedException: Hostname xxx not verified:
certificate: xxx
DN:xxx
subjectAltNames: []
at okhttp3.internal.io.RealConnection.connectTls(RealConnection.java:248)
at okhttp3.internal.io.RealConnection.establishProtocol(RealConnection.java:196)
at okhttp3.internal.io.RealConnection.buildConnection(RealConnection.java:171)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:111)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:187)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)


这是我的代码:

private OkHttpClient getClient() {
    OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
    builder.sslSocketFactory(getPinnedCertSslSocketFactory());
    return lBuilder.build();
  }



  private SSLSocketFactory getPinnedCertSslSocketFactory() {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");
      File trustStoreFile = new File(...);
      InputStream in = new FileInputStream(trustStoreFile);
      trusted.load(in, TRUSTSTORE_PW.toCharArray());
      SSLContext sslContext = SSLContext.getInstance("TLS");
      TrustManagerFactory trustManagerFactory = TrustManagerFactory
          .getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trustManagerFactory.init(trusted);
      sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
      return sslContext.getSocketFactory();
    } catch (Exception e) {
      LOGGER.error("getPinnedCertSslSocketFactory", e);
    }
    return null;
  }

public void doRequest() {
     OkHttpClient client = getClient();
     Request request = new Request.Builder().url(URL).post(BODY).build();
     client.newCall(request).execute();
}


任何想法如何解决这一问题?

最佳答案

builder.sslSocketFactory(getPinnedCertSslSocketFactory());


是不足够的。

尝试以下代码:

@SuppressLint("BadHostnameVerifier")
private static class TrustAllHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

builder.sslSocketFactory(getPinnedCertSslSocketFactory())
        .hostnameVerifier(new TrustAllHostnameVerifier());

关于android - OkHttp SSLPeerUnverifiedException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38451981/

10-12 13:57