首先我不得不承认我知道接受所有证书可以被认为没有安全性。我们有“真正的”证书,但仅限于我们的实时系统。我们测试系统上的证书是自签名的。所以只要我们在开发,我们就必须使用测试服务器,这迫使我禁用证书。
我在 Stackoverflow 和整个网络上看到了很多主题,它们都在尝试做同样的事情:接受 SSL 证书。然而,这些答案似乎都不适用于我的问题,因为我没有搞乱HTTPSUrlConnections
.
如果我正在发出请求,代码通常如下所示(为澄清而发表评论):
//creates an HTTP-Post with an URL
HttpPost post = createBaseHttpPost();
//loads the request Data inside the httpPost
post.setEntity(getHttpPostEntity());
//appends some Headers like user-agend or Request UUIDs
appendHeaders(post);
HttpClient client = new DefaultHttpClient();
//mResponse is a custom Object which is returned
//from the custom ResponseHandler(mResponseHandler)
mResponse = client.execute(post, mResponseHandler);
return mResponse;
我读到我应该注入自己的TrustManager
和X509HostnameVerivier
. 我这样创建它们:
private static final TrustManager[] TRUST_ALL_CERTS = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
}
};
private static X509HostnameVerifier ACCEPT_ALL_HOSTNAMES =
new X509HostnameVerifier() {
public void verify(String host, String[] cns, String[] subjectAlts)
throws SSLException {
}
public void verify(String host, X509Certificate cert) throws SSLException {
}
public void verify(String host, SSLSocket ssl) throws IOException {
}
public boolean verify(String host, SSLSession session) {
return true;
}
};
如果我像这样注入HostnameVerifier
我的请求(客户端是上面的 DefaultHttpClient)
SSLSocketFactory ssl = (SSLSocketFactory)client.getConnectionManager().getSchemeRegistry().getScheme("https").getSocketFactory();
ssl.setHostnameVerifier(ACCEPT_ALL_HOSTNAMES);
响应从“主机名**不匹配”变为“错误请求”。我想我必须设置 TrustManager,但我不知道在我的请求中设置它的位置,因为我没有使用在我查找它的所有地方提到的 HttpsUrlConnections。