android – 如何使用Retrofit发布HTTPS请求?

前端之家收集整理的这篇文章主要介绍了android – 如何使用Retrofit发布HTTPS请求?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通过这个构建了一个restAdapter:
return new RestAdapter.Builder()
            .setEndpoint("https://www.xyz.com/")
            .build()
            .create(SafeUserApi.class);

然后在SafeUserApi.class(这是一个接口)我有:

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

但它不起作用.我错过了什么?

我试过Postman并且它有效.但在我的设备中却没有.

我导入了这四个库:

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')

解决方法

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);
    }

}

这应该工作:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(YOUR_HTTPS_URL)
    .setClient(getUnsafeOkHttpClient())
    .build();

猜你在找的Android相关文章