Skip to content

Instantly share code, notes, and snippets.

@Kursulla
Last active November 13, 2018 16:58
Show Gist options
  • Save Kursulla/0fd3549a99b8f594da8d to your computer and use it in GitHub Desktop.
Save Kursulla/0fd3549a99b8f594da8d to your computer and use it in GitHub Desktop.
Self signing certificate: Android and Retrofit
Enabling communication with API if server has Self-Signed Certificate
dependencies {
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
}
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.setClient(new OkClient(SelfSigningClientBuilder.createClient()))
.build();
package ch.katzentisch.api;
import com.squareup.okhttp.OkHttpClient;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
@SuppressWarnings("unused")
public class SelfSigningClientBuilder {
@SuppressWarnings("null")
public static OkHttpClient configureClient(final OkHttpClient client) {
final TrustManager[] certs = new TrustManager[]{new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(final X509Certificate[] chain,
final String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(final X509Certificate[] chain,
final String authType) throws CertificateException {
}
}};
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, certs, new SecureRandom());
} catch (final java.security.GeneralSecurityException ex) {
}
try {
final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(final String hostname,
final SSLSession session) {
return true;
}
};
client.setHostnameVerifier(hostnameVerifier);
client.setSslSocketFactory(ctx.getSocketFactory());
} catch (final Exception e) {
}
return client;
}
public static OkHttpClient createClient() {
final OkHttpClient client = new OkHttpClient();
return configureClient(client);
}
}
@Yexi
Copy link

Yexi commented Jun 28, 2016

why these codes are error???

client.setHostnameVerifier(hostnameVerifier);
client.setSslSocketFactory(ctx.getSocketFactory());

@vivekgidmare
Copy link

@Yexi

httpClient.hostnameVerifier(hostnameVerifier);
httpClient.sslSocketFactory(sslContext.getSocketFactory());

@chrisenabled
Copy link

Bless!!!

@smihajlovski
Copy link

I also get error on

client.setHostnameVerifier(hostnameVerifier); client.setSslSocketFactory(ctx.getSocketFactory());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment