Skip to content

Instantly share code, notes, and snippets.

@luciofm
Created January 8, 2014 13:36
Show Gist options
  • Save luciofm/8316842 to your computer and use it in GitHub Desktop.
Save luciofm/8316842 to your computer and use it in GitHub Desktop.
In RestAdapter.Builder()
.setClient(new MyHttpClient(context.getApplicationContext()))
private class MyHttpClient extends UrlConnectionClient {
SSLContext sslContext = null;
SSLSocketFactory sslSocketFactory = null;
private final OkHttpClient client;
static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
public MyHttpClient(Context context) {
client = generateDefaultOkHttp();
try {
sslSocketFactory = trustAllFactory();
client.setSslSocketFactory(sslSocketFactory);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
SSLSocketFactory trustAllFactory()
throws NoSuchAlgorithmException, KeyManagementException {
if (!BuildConfig.DEBUG)
return defaultSSLFactory();
X509TrustManager trustManager = new X509TrustManager() {
@Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { trustManager }, null);
return sslContext.getSocketFactory();
}
private SSLSocketFactory defaultSSLFactory() {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, null, null);
} catch (GeneralSecurityException e) {
throw new AssertionError(); // The system has no TLS. Just give up.
}
return sslContext.getSocketFactory();
}
@Override
protected HttpURLConnection openConnection(Request request) throws IOException {
HttpURLConnection conn = client.open(new URL(request.getUrl()));
if (conn instanceof HttpsURLConnection && sslSocketFactory != null) {
((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
if (BuildConfig.DEBUG)
return true;
if (hostname.contentEquals("host.api.com"))
return true;
return false;
}
});
((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
}
return conn;
}
private OkHttpClient generateDefaultOkHttp() {
OkHttpClient okHttp = new OkHttpClient();
okHttp.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
okHttp.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
return okHttp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment