https restwebservice java,httpclient调用https webservice(rest) 忽略证书

最近做一个项目需要调用rest风格的webservice,但对方提供一个https的url,所以需要忽略证书去访问。httpclient4.3的api相比3.x改动挺大的,所以,把自己实现的分享出来。代码有些乱,大家参考下。有些方法没贴出来。

这个地方需要重生isTrusted方法,达到忽略本地证书的目的。

private  SSLConnectionSocketFactory buildSSLContext()

throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {

SSLContext sslcontext = SSLContexts.custom().setSecureRandom(new SecureRandom()).loadTrustMaterial(null, new TrustStrategy() {

public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {

return true;

}

}).build();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

return sslsf;

}

2. 这部分是具体调用webservice,功能是实现上传一个文件。

CloseableHttpClient httpclient = null;

HttpPost httppost = null;

try {

// create upload file

uploadFile = createUploaFile(user, appCenterUrl, buildTypeId);

//  get upload url

String uploadUrl = getUploadUrl(userMqa, mqaUrl);

// get httpclient

SSLConnectionSocketFactory sslsf = buildSSLContext();

httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

httppost = new HttpPost(uploadUrl);

httppost.addHeader(HttpHeaders.AUTHORIZATION, gererateEncoudAuth(userMqa));

FileBody bin = new FileBody(uploadFile);

StringBody comment = new StringBody("A binary file of some kind", ContentType.MULTIPART_FORM_DATA);

HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("resource", bin).addPart("comment", comment).build();

httppost.setEntity(reqEntity);

System.out.println("executing request " + httppost.getRequestLine());

CloseableHttpResponse httpResponse = httpclient.execute(httppost);

try {

System.out.println(httpResponse.getStatusLine().getStatusCode());

HttpEntity resEntity = httpResponse.getEntity();

if (resEntity != null) {

boolean flag = true;

System.out.println("Response content length: " + resEntity.getContentLength());

String resultStr = EntityUtils.toString(resEntity);

}

} finally {

if (httpResponse != null) {

httpResponse.close();

}

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (httppost != null) {

httppost.releaseConnection();

}

if (httpclient != null) {

httpclient.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

原文:http://microcosm.blog.51cto.com/8612978/1569027

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值