首先你需要生成你的证书文件,这里是步骤
项目应用程序类中的第二个定义 hurlStack 变量并在应用程序 OnCreate 方法中使用下一个方法
private void handleCertificationOnOlderDevices() {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new
BufferedInputStream(getAssets().open("porter_cert.crt"));
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
Log.d("certificate", ((X509Certificate) ca).getSubjectDN().toString());
} finally {
caInput.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
final X509TrustManager origTrustmanager =
(X509TrustManager) trustManagers[0];
TrustManager[] wrappedTrustManagers = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return origTrustmanager.getAcceptedIssuers();
}
public void checkClientTrusted(X509Certificate[] certs,
String authType)
{
try {
origTrustmanager.checkClientTrusted(certs, authType);
} catch (CertificateException e) {
e.printStackTrace();
}
}
public void checkServerTrusted(X509Certificate[] certs,
String authType)
{
try {
origTrustmanager.checkServerTrusted(certs, authType);
} catch (CertificateException e) {
e.printStackTrace();
}
}
}
};
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sslSocketFactory = context.getSocketFactory();
hurlStack = new HurlStack(null, sslSocketFactory);
} catch (Exception e) {
e.printStackTrace();
}
}
并在凌空请求队列上使用 hurlStack
public RequestQueue getRequestQueue() {
if (requestQueue == null)
requestQueue = Volley.newRequestQueue(getApplicationContext(),
hurlStack);
return requestQueue;
}
第三,如果您将 Glide 用于图像,您将收到与 glide 相关的 ssl 证书的第二个错误,您需要通过这种方式解决它
1 - 在应用程序中更新将您的 gilde 和 okhttp3 构建到这些版本
implementation "com.squareup.okhttp3:okhttp:3.8.1"
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation ('com.github.bumptech.glide:okhttp3-integration:4.9.0'){
exclude group: 'glide-parent'
}
2 - 将下一个类添加到您的项目中
@GlideModule
public class CustomGlideModule extends AppGlideModule {
@Override
public void registerComponents(Context context, Glide glide,
Registryregistry) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
OkHttpClient client =
SafeOkHttpClient.getSafeOkHttpClient(context);
OkHttpUrlLoader.Factory factory = new
OkHttpUrlLoader.Factory(client);
glide.getRegistry().replace(GlideUrl.class, InputStream.class,
factory);
}
}
}
现在 glide 可以很好地配合你了。