gpt4 book ai didi

java - SSLPeerUnverifiedException 与 httpClient

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:34 27 4
gpt4 key购买 nike

我正在尝试使用自签名证书测试安全的 http 连接...仅用于开发目的。但是我一直无法解决 peer not authenticated 异常,当然我已经看过关于这个异常的类似帖子,下面是我正在使用的当前实现:

public class SelfCertificatesSocketFactory extends SSLSocketFactory {

SSLContext sslContext = SSLContext.getInstance("TLS");

public SelfCertificatesSocketFactory(KeyStore trustStore) throws NoSuchAlgorithmException,UnrecoverableKeyException,KeyStoreException,KeyManagementException {
super(trustStore);

TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}

public X509Certificate[] getAcceptedIssuers() {
return null;
}
};




}

@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}



@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket,host,port,autoClose);
}



}

以及用法:

private DefaultHttpClient createHttpsClient(){
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);

SSLSocketFactory sf = new SelfCertificatesSocketFactory(trustStore);
//sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, sf));

ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
return new DefaultHttpClient(ccm);
} catch (Exception e) {
return new DefaultHttpClient();
}

}

但是它不起作用...我仍然遇到异常。我做错了什么?PD:我正在实现一个 Java Web 应用程序,这不是一个 Android 客户端。非常感谢。

最佳答案

您的代码创建的信任管理器实例似乎没有在任何地方使用,并且 KeyStore 实例似乎不包含任何信任 Material 。

与其做所有这些,您应该简单地利用 SSLSocketFactory 的功能。

TrustStrategy easyStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// eh, why not?
return true;
}
};
SSLSocketFactory sf = new SSLSocketFactory(easyStrategy);

关于java - SSLPeerUnverifiedException 与 httpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9101763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com