使用CertificatePinner改进okhttpclient

时间:2016-03-31 18:11:54

标签: android retrofit okhttp retrofit2 okhttp3

我正在使用Retrofit 2.0.0-beta3和OkHttp 3.0.0-RC1,面对琐碎的问题。我连接的HTTPS服务器工作正常,我使用CertificatePinner和OkHttp调用但不能使用Retrofit调用,即使我在Retrofit实例中设置相同的客户端

String hostname = "hostname";
CertificatePinner certificatePinner = new CertificatePinner.Builder()
        .add(hostname, "sha1/rNKiM/IsTzTMJ09jpMtPq4qP+Q8=")
        .add(hostname, "sha1/hL8+j9RH89wlAW7eNDSS1ZlZ8Z8=")
        .build();
OkHttpClient client = new OkHttpClient.Builder().certificatePinner(certificatePinner).build();

// This call works
OkHttpClient client = new OkHttpClient.Builder().certificatePinner(certificatePinner).build();
Request request = new Request.Builder()
    .url("https://" + hostname + "/api/me")
    .addHeader("Authorization", "Bearer token")
    .build();
okhttp3.Call call = client.newCall(request);
//execute call returns 200 with response

// This is not working and throwing SSL Connection Error
retrofit = new Retrofit.Builder()
        .baseUrl("https://" + hostname)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .client(client)
        .build();

1 个答案:

答案 0 :(得分:0)

这是app中的一个错误,因为在下面的代码之前创建了客户端:

ProviderInstaller.installIfNeeded(getApplication());

订单现已修复,代码正常。