Created
June 3, 2018 10:36
-
-
Save xingstarx/b71c920e288d06cb355d1c71cefdbf5d to your computer and use it in GitHub Desktop.
使用Retrofit OkHTTP不校验https自签名证书(全部不校验)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// copy from https://stackoverflow.com/a/49063199/5279354 | |
Retrofit retrofit = new Retrofit.Builder() | |
.baseUrl(YOUR_BASE_URL) | |
.client(getUnsafeOkHttpClient().build()) | |
.build(); | |
public static OkHttpClient.Builder 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(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); | |
builder.hostnameVerifier(new HostnameVerifier() { | |
@Override | |
public boolean verify(String hostname, SSLSession session) { | |
return true; | |
} | |
}); | |
return builder; | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment