Last active
November 21, 2018 12:39
-
-
Save fobidlim/9b587d17429464e7ad5561e78ff7302a to your computer and use it in GitHub Desktop.
Retrofit SSLHandShakeException
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
public class RetrofitHelper { | |
private static final String TAG = "RetrofitHelper"; | |
private static RetrofitHelper mInstance; | |
private Retrofit mRetrofit; | |
private RetrofitHelper() { | |
} | |
public static RetrofitHelper getInstance() { | |
if (mInstance == null) { | |
synchronized (RetrofitHelper.class) { | |
mInstance = new RetrofitHelper(); | |
} | |
} | |
return mInstance; | |
} | |
public void init() { | |
if (mRetrofit != null) { | |
Log.d(TAG, "Retrofit is already initialized"); | |
} | |
mRetrofit = getDefaultRetrofit(); | |
} | |
private Retrofit getDefaultRetrofit() { | |
OkHttpClient httpClient = new OkHttpClient.Builder().build(); | |
try { | |
SSLContext sc; | |
sc = SSLContext.getInstance("SSL"); | |
sc.init(null, new TrustManager[]{new X509TrustManager() { | |
@SuppressLint("TrustAllX509TrustManager") | |
@Override | |
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { | |
} | |
@SuppressLint("TrustAllX509TrustManager") | |
@Override | |
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
}}, new SecureRandom()); | |
HostnameVerifier hv = (hostname, session) -> true; | |
String workerClassName = "okhttp3.OkHttpClient"; | |
try { | |
Class workerClass = Class.forName(workerClassName); | |
Field hostnameVerifier = workerClass.getDeclaredField("hostnameVerifier"); | |
hostnameVerifier.setAccessible(true); | |
hostnameVerifier.set(httpClient, hv); | |
Field sslSocketFactory = workerClass.getDeclaredField("sslSocketFactory"); | |
sslSocketFactory.setAccessible(true); | |
sslSocketFactory.set(httpClient, sc.getSocketFactory()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return new Retrofit.Builder() | |
.baseUrl(BASE_URL) | |
.client(httpClient) | |
.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment