(1)最关键的代码
protected static SSLSocketFactory getSSLSocketFactory(Context context, int[] certificates) {
if (context == null) {
throw new NullPointerException("context == null");
}
//CertificateFactory用来证书生成
CertificateFactory certificateFactory;
try {
certificateFactory = CertificateFactory.getInstance("X.509");
//Create a KeyStore containing our trusted CAs
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
for (int i = 0; i < certificates.length; i++) {
//读取本地证书
InputStream is = context.getResources().openRawResource(certificates[i]);
keyStore.setCertificateEntry(String.valueOf(i), certificateFactory.generateCertificate(is));
if (is != null) {
is.close();
}
}
//Create a TrustManager that trusts the CAs in our keyStore
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
//Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
}
return null;
}
(2)添加证书,请求数据
int[] ints = {R.raw.service
};
OkHttpClient.Builder builder = new OkHttpClient.Builder().sslSocketFactory(SslContextFactory.getSSLSocketFactory(this, ints));
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())//增加返回值为Gson的支持(以实体类返回)
.baseUrl("https://api.tiantongjiaoyu.com")//换成自己的
.client(builder.build())
.build();
Api api = retrofit.create(Api.class);
api.getCourseList().enqueue(new Callback<KeChengModle>() {
@Override
public void onResponse(Call<KeChengModle> call, Response<KeChengModle> response) {
tv_des.setText(response.body().getResult().get(0).getName());
}
@Override
public void onFailure(Call<KeChengModle> call, Throwable t) {
}
});
(3)大功告成。