我正在为使用REST API的应用程序创建一些单元测试.当我尝试向服务器URL(https://some.server.com)发送HttpPost请求时,我得到了这个:
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:352)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:399)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
服务器具有经过验证的HTTPS证书.此外,当我在生产中运行它时,它工作正常.所以我认为它与JUnit和/或我的本地计算机有关.
我也在使用这个创建的HttpClient:
public static class WebClientDevWrapper {
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null,new TrustManager[]{tm},null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https",ssf,443));
return new DefaultHttpClient(ccm,base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
AFAIK,如果我使用上面的代码创建一个HTTPClient,它应该避免SSLPeerUnverifiedException,但它似乎无法正常工作.
那么我该如何解决这个问题呢?我已经尝试了更多方法来创建不抱怨SSL证书的HttpClients,但到目前为止还没有任何工作.
最佳答案
原文链接:https://www.f2er.com/java/437890.html