Retrofit2对https请求的实现(干货)

来源:互联网 发布:美国为什么强大知乎 编辑:程序博客网 时间:2024/06/06 05:48

由于项目上传到GooglePlay时被提醒传输数据方式不安全,故改用https加密传输。这里我的项目里用到Retrofit2.2.0,但Retrofit本身的okhttp不能直接请求证书不安全的https,所以得采取一些应急措施。

首先我们在androidstudio里的gradle依赖Retrofit,如下:

compile 'com.squareup.retrofit2:retrofit:2.2.0'compile 'com.squareup.retrofit2:converter-gson:2.2.0'

然后把生成的证书文件key放入项目目录的raw文件夹下,没有raw的话就新建一个即可,这里key是bks后缀的,不是的话自行google如何转换成bks。



这里我们需添加一个新类,为取得SSL一些实例:

public class SslContextFactory {    private static final String CLIENT_TRUST_PASSWORD = "*******";//信任证书密码    private static final String CLIENT_AGREEMENT = "TLS";//使用协议    private static final String CLIENT_TRUST_MANAGER = "X509";    private static final String CLIENT_TRUST_KEYSTORE = "BKS";    SSLContext sslContext = null;    public SSLContext getSslSocket(Context context) {        try {//取得SSL的SSLContext实例            sslContext = SSLContext.getInstance(CLIENT_AGREEMENT);//取得TrustManagerFactory的X509密钥管理器实例            TrustManagerFactory trustManager = TrustManagerFactory.getInstance(CLIENT_TRUST_MANAGER);//取得BKS密库实例            KeyStore tks = KeyStore.getInstance(CLIENT_TRUST_KEYSTORE);            InputStream is = context.getResources().openRawResource(R.raw.key);            try {                tks.load(is, CLIENT_TRUST_PASSWORD.toCharArray());            } finally {                is.close();            }//初始化密钥管理器            trustManager.init(tks);//初始化SSLContext            sslContext.init(null, trustManager.getTrustManagers(), null);        } catch (Exception e) {            Log.e("SslContextFactory", e.getMessage());        }        return sslContext;    }}


有了这个类,我们就可以完成retrofit2对https的请求了,下面做出处理:

//retrofit2访问https        SSLSocketFactory sslSocketFactory = new SslContextFactory().getSslSocket(context).getSocketFactory();        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory);        Retrofit retrofit = new Retrofit.Builder()                .baseUrl("https://test.pengfff/") //url自行配置                .client(okHttpClient.build())                .build();        PostService postService = retrofit.create(PostService.class);        Call<ResponseBody> call = postService.postFormUrlEncoded(name,pwd);        call.enqueue(new Callback<ResponseBody>()        {            @Override            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {                String result = response.body().toString();            }            @Override            public void onFailure(Call<ResponseBody> call, Throwable t) {                Toast.makeText(mcontext, t.toString(), Toast.LENGTH_SHORT).show();            }        });    }    public interface PostService {        @POST("test")        @FormUrlEncoded        Call<ResponseBody> postFormUrlEncoded(@Field("name") String name, @Field("pwd") String pwd);    }

这是一个很普通的POST表单请求,请求方式为HTTPS

最后测试返回结果成功,大家有问题可以评论下面提问,谢谢。


2 0