gpt4 book ai didi

android - 在 Android 中获取 SSLPeerUnverifiedException

转载 作者:行者123 更新时间:2023-11-30 03:33:53 24 4
gpt4 key购买 nike

当我尝试使用 HTTPs 连接进行连接时,出现 SSL Peer Unverified Exception。我是 HTTP 的新手。我的代码是:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpPost httppost = new HttpPost("https://server.example.com/Login");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("LoginId",uname));
nameValuePairs.add(new BasicNameValuePair("Password",pass));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {

}
Log.i("zacharia", "Response :"+EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
}

最佳答案

SSL Peer Unverified Exception 可能由于多种原因而抛出,最常见的是当服务器发送的证书是自签名证书而不是授权 CA 签名的证书时,如果这是问题,android 中的常见方法是将证书添加到 Trusted Certificates 链中,然后按如下方式发出请求:

KeyStore selfsignedKeys = KeyStore.getInstance("BKS");
selfsignedKeys.load(context.getResources().openRawResource(R.raw.selfsignedcertsbks),
"genericPassword".toCharArray());
TrustManagerFactory trustMgr = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustMgr.init(selfsignedKeys);
SSLContext selfsignedSSLcontext = SSLContext.getInstance("TLS");
selfsignedSSLcontext.init(null, trustMgr.getTrustManagers(), new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(selfsignedSSLcontext.getSocketFactory());
URL serverURL = new URL("https://server.example.com/endpointTest");
HttpsURLConnection serverConn = (HttpsURLConnection)serverURL.openConnection();

考虑到这种方法仅在您确定证书未由 CA 签名时才适用,并且为了使其正常工作,您需要自己拥有证书,将其放入 BKS keystore (供 android 读取它),然后使用“接受”该自签名证书的 SSL 上下文打开一个 HttpURLConnection,因为 DefaultHttpClient 不会基于默认 SSLContext 处理这些请求。

如果您想了解有关 SSL 的更多信息,我建议您阅读 Jeff Six Editorial O'Reilly 撰写的“Android 平台的应用程序安全”一书...

问候!

关于android - 在 Android 中获取 SSLPeerUnverifiedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16952950/

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