您的位置:首页 > 理论基础 > 计算机网络

HTTPS访问站点,出现证书问题解决(转载)

2010-01-16 17:48 423 查看
用URLConnection获取一个Https站点的东西 老是抛出异常说证书认证不过 不过对服务迁移性的考虑 又不想导入证书到JRE里面(总不会说出现紧急情况 需要搬迁到其他服务器 还要我记得去导入证书吧) 最奇怪的是 Windows下运行的好好的 没有什么异常 一去Linux就出错
最后没有办法 只有 强制绕过这个检查了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;

public class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}

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

public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
1
2
3
4
5
6
7
8
9
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
// 直接Pass
return true;
}
}
就是要检查的时候 让他直接返回true 通过验证就OK了

在建立连接的时候 还要设置一下这个管理器

1
2
3
4
5
6
7
8
9
SSLContext context = SSLContext.getInstance("SSL");
context.init(null,new TrustManager[] { new TrustAnyTrustManager() },
new SecureRandom());
// 获取URL 进行连接
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(context.getSocketFactory());
connection.setHostnameVerifier(new TrustAnyHostnameVerifier());
connection.connect();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: