Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post HTTPS request using Retrofit?

I build a restAdapter by this:

    return new RestAdapter.Builder()
            .setEndpoint("https://www.xyz.com/")
            .build()
            .create(SafeUserApi.class);

then in the SafeUserApi.class (which is an interface) I have:

public interface SafeUserApi {
    @POST("/api/userlogin")
    void getUserLogin(@Body UserserLogin userLogin, Callback<LoginResult> cb);
}

But it does not work. Did I miss something?

I tried with Postman and it works. But in my device it doesn't.

I have these four library imported:

compile files('libs/okhttp-2.1.0.jar')
compile files('libs/okhttp-urlconnection-2.1.0.jar')
compile files('libs/okio-1.0.1.jar')
compile files('libs/retrofit-1.8.0.jar')
like image 481
Derekyy Avatar asked Dec 31 '14 04:12

Derekyy


1 Answers

public static OkHttpClient getUnsafeOkHttpClient() {

    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[0];
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts,
                new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext
                .getSocketFactory();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient = okHttpClient.newBuilder()
                .sslSocketFactory(sslSocketFactory)
                .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();

        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

This should work:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(YOUR_HTTPS_URL)
    .setClient(getUnsafeOkHttpClient())
    .build();
like image 185
Swami Avatar answered Sep 21 '22 07:09

Swami