gpt4 book ai didi

Android:发出 Https 请求

转载 作者:IT王子 更新时间:2023-10-28 23:28:30 25 4
gpt4 key购买 nike

在发出 Https 请求时,如何避免“javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated”异常和 Android Apache lib 间隙“构造函数 SSLSocketFactory(SSLContext) 未定义”?

最佳答案

此方法接受一个 HttpClient 实例并返回一个准备好 https 的 HttpClient 实例。

 private HttpClient sslClient(HttpClient client) {
try {
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new MySSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, client.getParams());
} catch (Exception ex) {
return null;
}
}

由于Android org.apache.http.conn.ssl.SSLSocketFactory 没有SSLSocketFactory(SSLContext) 构造函数,所以我将类扩展如下。

 public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");

public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);

TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};

sslContext.init(null, new TrustManager[] { tm }, null);
}

public MySSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}

@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}

这里的优秀文章:http://javaskeleton.blogspot.com/2010/07/avoiding-peer-not-authenticated-with.html

还有一些帮助:Trusting all certificates using HttpClient over HTTPS

关于Android:发出 Https 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7622004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com