2

当我尝试使用 HTTPS 连接进行连接时,我收到 SSL Peer Unverified Exception。我是 HTTPS 的新手。我的代码是:

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) {
}
4

1 回答 1

1

可能会抛出 SSL Peer Unverified Exception 有几个原因,最常见的是当服务器发送的证书是自签名证书而不是授权 CA 签名的证书时,如果这是问题,android 中的常见方法是添加证书到受信任的证书链,然后按如下方式发出请求:

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 密钥库(供 android 读取)和然后使用“接受”该自签名证书的 SSL 上下文打开 HttpURLConnection,因为 DefaultHttpClient 不会根据默认 SSLContext 处理这些请求。

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

问候!

于 2013-06-06T03:43:24.363 回答