http client4 访问无效证书的HTTPS网站

本文介绍了一种通过自定义X509TrustManager来忽略SSL证书验证的方法,并展示了如何使用HttpClient发起HTTPS请求的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

 

};

 

StringBuffer result = new StringBuffer();

try {

HttpClient client = new DefaultHttpClient();

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

ctx.init(null, new TrustManager[] { tm }, null);

SSLSocketFactory ssf = new SSLSocketFactory(ctx);

ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

ClientConnectionManager ccm = client.getConnectionManager();

SchemeRegistry sr = ccm.getSchemeRegistry();

sr.register(new Scheme("https", ssf, 443));

HttpClient sslClient = new DefaultHttpClient(ccm,client.getParams());

HttpPost post=new HttpPost(Constant.HOST);

HttpResponse response = sslClient.execute(post)

status = response.getStatusLine().getStatusCode();

HttpEntity entity = response.getEntity();

BufferedReader rd = new BufferedReader(new InputStreamReader(

entity.getContent(), HTTP.UTF_8));

String tempLine = rd.readLine();

while (tempLine != null) { 

result.append(tempLine);

tempLine = rd.readLine();

}

} catch (Exception e) {

throw new ServiceException("请求出错");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值