我尝试使用排球做https请求 但我收到此错误回复
javax.net.ssl.SSLHandshakeException:> java.security.cert.CertPathValidatorException:用于认证的信任锚>找不到路径。
这条消息意味着什么?
答案 0 :(得分:2)
出现该消息是因为您需要将证书添加到您的齐射https请求中。
为此,请在排球时将HurlStack
添加到您的请求中。
HurlStack hurlStack = new HurlStack() {
@Override
protected HttpURLConnection createConnection(java.net.URL url)
throws IOException {
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super
.createConnection(url);
try {
httpsURLConnection
.setSSLSocketFactory(getSSLSocketFactory(context));
// httpsURLConnection.setHostnameVerifier(getHostnameVerifier());
} catch (Exception e) {
e.printStackTrace();
}
return httpsURLConnection;
}
};
getSSLSocketFactory
使用此功能。
private SSLSocketFactory getSSLSocketFactory(Context context)
throws CertificateException, KeyStoreException, IOException,
NoSuchAlgorithmException, KeyManagementException {
// the certificate file will be stored in \app\src\main\res\raw folder path
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = context.getResources().openRawResource(
R.raw.YourCertificate);
Certificate ca = cf.generateCertificate(caInput);
caInput.close();
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf
.getTrustManagers());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null);
return sslContext.getSocketFactory();
}
TrustManager
使用此方法:
private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
return new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return originalTrustManager.getAcceptedIssuers();
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager
.checkClientTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkClientTrusted", e.toString());
}
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager
.checkServerTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkServerTrusted", e.toString());
}
}
} };
}
最后在RequestQueue
调用hurlstack:
RequestQueue requestQueue = Volley.newRequestQueue(context, hurlStack);
requestQueue.add(Your Request);