httpclient调用https
httpclient调用https报错:
Exception in thread "main" java.lang.Exception: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
代码:
package com.taiping; import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Map; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol; import com.taiping.base.facility.tool.JAXBTool;
import com.taiping.base.util.IOTool;
import com.taiping.partner.antgroup.DTO.ali.request.RequestCheckDoc;
import com.taiping.partner.antgroup.DTO.ali.request.RequestCheckbillDoc;
import com.taiping.z.HTTPSSecureProtocolSocketFactory; public class HttpXmlSender_189_1_LOCAL
{
public static void main(String[] args) throws Exception
{
// 核保:"test-antgroup-underwrite-12602-5.xml";
// 出单:"test-antgroup-issue-12602-5.xml"; test-antgroup-issue-EBB.xml test-antgroup-issue-YaZhouLYYW.xml
String file = "test-antgroup-underwrite-EBB.xml"; String path = HttpXmlSender_189_1_LOCAL.class.getResource("/template/"+file).getPath();
System.out.println("path : "+path); // 请确认编码方式
String encode = "utf-8";
String xml = IOTool.readFile(path, encode); //请确认编码方式 // localhost本地
// String url = "http://localhost:8000/taiping-sol-mall/services/antgroup/entrance";
// UAT环境
String url = "https://baoxian.itaiping.com/services/antgroup/entrance";
// String url = "http://10.1.17.95:7002/services/antgroup/entrance"; // 生产环境
// String url = "http://baoxian.cntaiping.com/partner/partnerEntrance.action";
// 生产环境IP访问
// String url = "http://10.4.233.6:8003/partner/partnerEntrance.action"; String policyNo ="2016ANTGROUP_XLH08171";
xml = xml.replaceAll("#policyNo#", policyNo); // 1、解析报文
RequestCheckDoc requestCheckDoc = null;
RequestCheckbillDoc requestCheckbillDoc = null;
try {
if (xml.indexOf("underwrite") > -) {
requestCheckDoc = (RequestCheckDoc) JAXBTool.unmarshal(xml, RequestCheckDoc.class);
requestCheckDoc.setSignature();
xml = JAXBTool.marshal(requestCheckDoc);
}else {
requestCheckbillDoc = (RequestCheckbillDoc) JAXBTool.unmarshal(xml, RequestCheckbillDoc.class);
requestCheckbillDoc.setSignature();
xml = JAXBTool.marshal(requestCheckbillDoc);
}
System.out.println("requestXml:\n"+xml);
} catch (Exception e) {
e.printStackTrace();
} String responseXml = new HttpXmlSender_189_1_LOCAL().post(url,xml,encode,policyNo);
System.out.println("responseXml:\n"+responseXml);
} /**
* post 方法
* @param url
* @param params
* @return
*/
public String post(String url, Object content, String encode,String policyNo) throws Exception { String responseMsg = "";
byte[] responseBody = null;
HttpClient httpclient = new HttpClient(); // 为支持https step1
Protocol https = new Protocol("https", new HTTPSSecureProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", https); PostMethod httpPost = new PostMethod(url);
httpPost.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
httpPost.setRequestHeader("ContentType", "application/xml;charset=GBK");
// 设置连接超时时间(单位毫秒)
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout();
// 设置读数据超时时间(单位毫秒)
httpclient.getHttpConnectionManager().getParams().setSoTimeout();
try {
httpPost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(, false));
// servlet
if (content instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>)content;
NameValuePair[] param = new NameValuePair[map.size()]; int index = ;
for (Map.Entry<String, String> entry : map.entrySet()) {
param[index] = new NameValuePair(entry.getKey(),URLEncoder.encode(entry.getValue(), "GBK"));
} httpPost.setRequestBody(param);
}
// rest
else {
httpPost.setRequestEntity(new StringRequestEntity((String)content,"application/xml", encode));
// System.out.println("=========================================================");
// System.out.println("request by rest ......");
} // post
int statusCode = httpclient.executeMethod(httpPost);
// 为支持https step1 over
Protocol.unregisterProtocol("https"); System.out.println("policyNo:"+policyNo+",statusCode:"+statusCode);
// success
if (statusCode == HttpStatus.SC_OK) {
responseBody = httpPost.getResponseBody();
}
// failure
else {
responseMsg = String.valueOf("statusCode:"+statusCode);
}
} catch (HttpException e) {
throw new Exception(e.getMessage());
} catch (IOException e) {
throw new Exception(e.getMessage());
} catch (Exception e) {
throw new Exception(e.getMessage());
} finally {
httpPost.releaseConnection();
} if (responseBody != null) {
responseMsg = new String(responseBody, encode);
}
return responseMsg;
}
}
HTTPSSecureProtocolSocketFactory:
package com.taiping.z;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /**
* httpclient https
*
*/
public class HTTPSSecureProtocolSocketFactory implements ProtocolSocketFactory {//SecureProtocolSocketFactory
private SSLContext sslcontext = null; private SSLContext createSSLContext() {
SSLContext sslcontext = null;
try {
sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null,
new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return sslcontext;
} private SSLContext getSSLContext() {
if (null == this.sslcontext) {
this.sslcontext = createSSLContext();
}
return this.sslcontext;
} public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(socket, host,
port, autoClose);
} public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(host, port);
} public Socket createSocket(String host, int port, InetAddress clientHost,
int clientPort) throws IOException, UnknownHostException {
return getSSLContext().getSocketFactory().createSocket(host, port,
clientHost, clientPort);
} public Socket createSocket(String host, int port, InetAddress localAddress,
int localPort, HttpConnectionParams params) throws IOException,
UnknownHostException, ConnectTimeoutException {
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
SocketFactory socketfactory = getSSLContext().getSocketFactory();
if (timeout == ) {
return socketfactory.createSocket(host, port, localAddress,
localPort);
} else {
Socket socket = socketfactory.createSocket();
SocketAddress localaddr = new InetSocketAddress(localAddress,
localPort);
SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.bind(localaddr);
socket.connect(remoteaddr, timeout);
return socket;
}
} private static 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[] {};
}
} }
httpclient调用https的更多相关文章
- java 通过httpclient调用https 的webapi
java如何通过httpclient 调用采用https方式的webapi?如何验证证书.示例:https://devdata.osisoft.com/p...需要通过httpclient调用该接口, ...
- 在 IIS 6 和 IIS 7中配置Https,设置WCF同时支持HTTP和HTPPS,以及使用HttpWebRequest和HttpClient调用HttpS
IIS 7 ,给IIS添加CA证书以支持https IIS 6 架设证书服务器 及 让IIS启用HTTPS服务 WCF IIS 7中配置HTTPS C#利用HttpWebRequest进行post请求 ...
- Java 使用 HttpClient调用https 最新源码 JDK7+ apache4.3+
在项目使用https方式调用别人服务的时候,以前要写很多的代码,现在框架封装了很多,所以不用再写那么多了. 网上看了一下,都是很老的版本,用过时的DefaultHttpClient. 以spring为 ...
- Java调用Http/Https接口(4)--HttpClient调用Http/Https接口
HttpClient是Apache HttpComponents项目下的一个组件,是Commons-HttpClient的升级版,两者api调用写法也很类似.文中所使用到的软件版本:Java 1.8. ...
- 使用HttpClient携带pfx证书调用HTTPS协议的WebService
调用第三方服务时,厂商提供了一个WSDL文件.调用的地址和一个后缀为pfx的证书文件,通过SOUPUI记载证书是可以正常调用WebService服务,那么如何将该服务转换为代码呢? 咨询了厂商的支持, ...
- [转]java 关于httpclient 请求https (如何绕过证书验证)
原文:http://www.blogjava.net/hector/archive/2012/10/23/390073.html 第一种方法,适用于httpclient4.X 里边有get和post两 ...
- 用HttpClient发送HTTPS请求报SSLException: Certificate for <域名> doesn't match any of the subject alternative names问题的解决
最近用server酱-PushBear做消息自动推送,用apache HttpClient做https的get请求,但是代码上到服务器端就报javax.net.ssl.SSLException: Ce ...
- Httpclient 支持https(转)
参考:https://jingyan.baidu.com/article/154b46317353d228ca8f4112.html 参考:https://www.jianshu.com/p/a444 ...
- 关于httpclient 请求https (如何绕过证书验证)
第一种方法,适用于httpclient4.X 里边有get和post两种方法供你发送请求使用.导入证书发送请求的在这里就不说了,网上到处都是 import java.io.BufferedReader ...
随机推荐
- Linux_用户/用户组
一.用户添加 1. 账号添加 [root@hadoop09-linux tmp]# useradd eRrsr 这时/etc/passwd文件中会追加该用户项,并且在/home文件夹下自动生成该属于 ...
- js实现事件模型bind与trigger
function Emitter() { this._listener = [];//_listener[自定义的事件名] = [所用执行的匿名函数1, 所用执行的匿名函数2] } //注册事件 Em ...
- Spark cache 和 persist
1)RDD的cache()方法其实调用的就是persist方法,缓存策略均为MEMORY_ONLY:2)可以通过persist方法手工设定StorageLevel来满足工程需要的存储级别:3)cach ...
- HDU1011 树形DP
Starship Troopers Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...
- 实验验证redis的快照和AOF
安装配置redis http://www.cnblogs.com/myrunning/p/4222385.html 验证redis的主从复制 http://www.cnblogs.com/myrunn ...
- 高德地图 室内地图 API 的一些坑
开发指南 http://lbs.amap.com/api/javascript-api/guide/create-map/indoormap/ demo 大全: http://lbs.amap.com ...
- JSTL标签使用说明
使用jstl需进行以下操作 a.下载jstl. b.解压jar文件将jstl.jar和standard.jar文件放到项目lib文件夹. c.在需要使用jstl地方引用标签库,比如在jsp页面引用以下 ...
- Mac OS X 背后的故事
Mac OS X 背后的故事 作者: 王越 来源: <程序员> 发布时间: 2013-01-22 10:55 阅读: 25840 次 推荐: 49 原文链接 [收藏] ...
- iScroll.js几个问题及其解决办法
1.在一个页面中需要点击tab切换,而且每个切换的内容都需要下拉刷新加载,这个时候需要在点击的时候用到myScroll.refresh();这个函数,刷新iScroll.js这个函数. 2.在页面中有 ...
- Nhiberate (二) 搭项目
使用: visual studio 2015 ;SQL SERVER 2012. 参考.测试可用 其中有点不太一样的地儿, ISession 的泛型方法: 用了 QueryOver<>,转 ...