在Android中获取SSLPeerUnverifiedException

时间:2013-06-06 02:47:52

标签: android ssl https http-post

当我尝试使用HTTPs Connection进行连接时,我收到了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) {
}

1 个答案:

答案 0 :(得分: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平台的应用程序安全性”一书......

问候!