Java的HttpClient如何去支持无证书访问https

 我来答
匿名用户
2016-07-04
展开全部
httpURLConnection.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
httpURLConnection.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
// 直接返回true
return true;
}
});//解决由于服务器证书问题导致HTTPS无法访问的情况
public static class BaseHttpSSLSocketFactory extends SSLSocketFactory {
private SSLContext getSSLContext() {
return createEasySSLContext();
}

@Override
public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2,
int arg3) throws IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}

@Override
public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}

@Override
public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1);
}

@Override
public Socket createSocket(String arg0, int arg1) throws IOException,
UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1);
}

@Override
public String[] getSupportedCipherSuites() {
// TODO Auto-generated method stub
return null;
}

@Override
public String[] getDefaultCipherSuites() {
// TODO Auto-generated method stub
return null;
}

@Override
public Socket createSocket(Socket arg0, String arg1, int arg2, boolean arg3)
throws IOException {
return getSSLContext().getSocketFactory().createSocket(arg0, arg1,
arg2, arg3);
}

private SSLContext createEasySSLContext() {
try {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null,
new TrustManager[] { MyX509TrustManager.manger }, null);
return context;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static class MyX509TrustManager implements X509TrustManager {

static MyX509TrustManager manger = new MyX509TrustManager();

public MyX509TrustManager() {
}

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

public void checkClientTrusted(X509Certificate[] chain, String authType) {
}

public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
仍殊qx
2016-07-04 · 超过10用户采纳过TA的回答
知道答主
回答量:88
采纳率:0%
帮助的人:19.6万
展开全部
来学习就知道啦~ 不学习以后会遇到更多的问题
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式