首先我们在androidstudio里的gradle依赖Retrofit,如下:
compile'com.squareup.retrofit2:retrofit:2.2.0'
compile'com.squareup.retrofit2:converter-gson:2.2.0'
然后把生成的证书文件key放入项目目录的main/assets文件夹下,没有的话就新建一个即可,这里key是cet后缀的,网上说有的是要自行google如何转换成bks。
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);
}