我有一个例外:没有同行证书
当我询问谷歌时,我得到了解决方案,我信任所有证书。但这个问题的答案是,它是不安全的。
所以我给班级打电话:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpClient 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);
Log.v("URL:", Url[0]);
HttpPost post = new HttpPost(Url[0]);
post.addHeader("Username", Url[1]);
post.addHeader("Passwort", Url[2]);
HttpResponse getResponse = httpClient.execute(post); //Wirft Exception
HttpEntity responseEntity = getResponse.getEntity();
UserID = Integer.parseInt(responseEntity.getContent().toString());
这是我的课:
class MyHttpClient extends DefaultHttpClient {
final Context context;
public MyHttpClient(Context context) {
this.context = context;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", (SocketFactory) newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = context.getResources().openRawResource(R.raw.mykey);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "PASSWORT".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// [url=http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506]Chapter2.Connection management[/url]
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
我发现了 SSLPeerUnverifiedException 的另一个可能原因:没有对等证书
如果您的模拟器运行的日期早于创建证书的日期,您可能会遇到此异常。
我的证书于 7 月 10 日生效,但模拟器的当前日期为 5 月 7 日。
我不知道为什么我的模拟器将日期设置为 5 月 7 日,因为它应该从网络获取时间,但这是另一个问题。
只是想我应该分享一下,以防它可以帮助其他人避免浪费几天的时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)