javax.net.ssl.SSLPeerUnverifiedException: Hostname 10.1.82.151 not verified android怎么信任证书...
时间: 2024-03-10 22:43:39 浏览: 170
Android中信任SSL证书的步骤如下:
1. 将证书文件放到Android项目的assets文件夹下。
2. 创建一个TrustManager来处理证书。
```java
public class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
```
3. 创建一个SSLContext实例,并使用TrustManager初始化它。
```java
try {
InputStream inputStream = context.getAssets().open("证书文件名");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(inputStream);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", certificate);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
trustManagerFactory.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
```
4. 在请求时设置HTTPS连接方式。
```java
URL url = new URL("https://www.example.com");
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setConnectTimeout(5000);
httpsURLConnection.setReadTimeout(5000);
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
```
这样就可以信任SSL证书了。
阅读全文