Skip to content

Instantly share code, notes, and snippets.

@loisaidasam
Created January 13, 2015 06:52
Show Gist options
  • Save loisaidasam/d4caf3659c8fa7a38222 to your computer and use it in GitHub Desktop.
Save loisaidasam/d4caf3659c8fa7a38222 to your computer and use it in GitHub Desktop.

Big fan of Retrofit, but have a staging server that has an invalid SSL cert?

Fear not! Just use the AllCertsValidClient!

Example usage:

Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .create();
AllCertsValidClient client = new AllCertsValidClient();
RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(host)
    .setConverter(new GsonConverter(gson))
    .setClient(client)
    .build();
service = restAdapter.create(MyApiService.class);

Have fun, and be safe! (don't use this thing in production environments!)

package com.example;
import java.io.IOException;
import java.net.HttpURLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import retrofit.client.Request;
import retrofit.client.UrlConnectionClient;
// For a staging server with an invalid cert,
// we need to use a custom hostname verifier
// BE CAREFUL WITH THIS!!!
// https://developer.android.com/training/articles/security-ssl.html
public class AllCertsValidClient extends UrlConnectionClient {
@Override
protected HttpURLConnection openConnection(Request request) throws IOException {
HttpsURLConnection connection = (HttpsURLConnection) super.openConnection(request);
connection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return connection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment