Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?

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