基于java 使用http-post方式请求https webservice接口
2017-06-09 09:43
603 查看
本文章记录请求https接口的两种方式,安全证书默认全部接收。
本文记录两种请求https接口的方法,方法1经测试为可行,方法二由于缺jar包最后没有使用。希望可以帮到有需要的朋友。第二种方式:
/**
* 请求https的接口
*
* @param url 接口地址
* @param requestSoap 请求报文
* @param charSet 编码方式
* @return
* @throws Exception
*/
public static Map<String,Object> doPost(String url,String requestSoap,String charSet) throws Exception{
String result ="";
int timeOut=0;
CloseableHttpClient closeableHttpClient = createHttpsClient();
// 建立HttpPost对象
PostMethod postMethod = new PostMethod(url);
HttpPost httppost = new HttpPost(url);
byte[] b = new byte[0];
try {
b = requestSoap.getBytes(charSet);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
InputStream is = new ByteArrayInputStream(b, 0, b.length);
HttpEntity httpEntity = new InputStreamEntity(is, b.length);
httppost.setEntity(httpEntity);
Map<String,Object> resultMap =new HashMap<>();
try{
//发送Post,并返回一个HttpResponse对象
logger.info("开始发送请求");
HttpResponse httpResponse = closeableHttpClient.execute(httppost);
HttpEntity httpEntity2 = httpResponse.getEntity();
// 如果状态码为200,就是正常返回
int rspCode=httpResponse.getStatusLine().getStatusCode();
if (rspCode== HttpStatus.SC_OK) {
result= EntityUtils.toString(httpEntity2);
// 得到返回的字符串
logger.info("响应成功:"+result);
resultMap.put("responseCode", rspCode);
resultMap.put("responseXml", result);
}else {
result = EntityUtils.toString(httpEntity2);
resultMap.put("responseCode", rspCode);
resultMap.put("responseXml", result);
// 得到返回的字符串
}
//关闭连接
closeableHttpClient.close();
}catch(IOException e) {
logger.info("执行http请求失败", e);
}
return resultMap;
}
/**
* 处理https请求安全证书问题(默认接受所有证书)
*
* @return
* @throws Exception
*/
public static CloseableHttpClient createHttpsClient() throws Exception {
X509TrustManager x509mgr = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// 设置超时时间
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000).setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setStaleConnectionCheckEnabled(true).build();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { x509mgr },
new java.security.SecureRandom());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return HttpClients.custom().setSSLSocketFactory(sslsf)
.setDefaultRequestConfig(defaultRequestConfig).build();
}
第二种方式:
/**
* 字符串转OMElement
*
* @param xmlStr
* @param encoding
* @return
*/
public static OMElement toOMElement(String xmlStr, String encoding) {
OMElement xmlValue;
try {
xmlValue = new StAXOMBuilder(new ByteArrayInputStream(
xmlStr.getBytes(encoding))).getDocumentElement();
return xmlValue;
} catch (Exception e) {
return null;
}
}
public static void testDocument(String requestXml, String url) {
logger.info("--------into SoapUtil testDocument-------");
try {
// https方式访问webservices
// System.setProperty("javax.net.ssl.trustStorePassword",
// "netconfig");
System.setProperty("javax.net.ssl.trustStore",
"/uniproxy/jdk1.7.0_80/jre/lib/security/nciic.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
// String url =
// "http://localhost:8080/axis2ServerDemo/services/StockQuoteService";
// String url =
// "https://test.bjp2p.com.cn:8443/platformService?wsdl";
Options options = new Options();
// 指定调用WebService的URL
EndpointReference targetEPR = new EndpointReference(url);
options.setTo(targetEPR);
// options.setAction("urn:getPrice");
// options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
ServiceClient sender = new ServiceClient();
sender.setOptions(options);
OMFactory fac = OMAbstractFactory.getOMFactory();
/*
* String tns = "http://supervise.service.app.mp.zkbc.net/"; //
* 命名空间,有时命名空间不增加没事,不过最好加上,因为有时有事,你懂的 OMNamespace omNs =
* fac.createOMNamespace(tns, "");
*/
OMElement method = toOMElement(requestXml, "utf-8");
/*
* OMElement symbol = fac.createOMElement("arg0", omNs);
*
* symbol.addChild(fac.createOMText(symbol, "fylcws"));
* method.addChild(symbol); method.build(); OMElement symbol1 =
* fac.createOMElement("arg1", omNs);
*
* symbol1.addChild(fac.createOMText(symbol1, "fylcws@4r1"));
* method.addChild(symbol1); method.build();
*/
OMElement result;
result = sender.sendReceive(method);
logger.info("testDocument获取到返回-----------:" + result.toString());
} catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// return result;
}
相关文章推荐
- Http使用post方式提交数据(使用java标准接口)
- JAVA post和get方式请求远程HTTP接口
- Java 通过HttpClient 带证书方式请求Https协议网站 (Post方式带xml文档,Get以及Delete方式)
- Java基础知识强化之网络编程笔记18:Android网络通信之 使用HttpClient的Post / Get 方式读取网络数据(基于HTTP通信技术)
- java使用Post和Get方式提交Http请求通用
- Java基础知识强化之网络编程笔记17:Android网络通信之 使用Http的Post方式读取网络数据(基于HTTP通信技术)
- Java 以post请求方式通过json格式调用Webservice接口
- 使用Java原生API编写发送HTTP_POST请求的工具类
- 使用HTTP POST请求12306网站接口查询火车车次API
- nodejs的http.request使用post方式提交数据请求
- 【使用Java原生API编写发送HTTP_POST请求的工具类】
- JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求
- 使用HttpWebRequest发送自定义POST请求(以http方式推送消息)
- JAVA Socket 实现HTTP与HTTPS客户端发送POST与GET方式请求
- 利用httplib.HTTPSConnection 发送post请求的方式
- 使用java代码发送HTTP Post请求
- Java HTTP方式请求.NET WebService服务总结
- 使用HTTP POST请求12306网站接口查询火车车次API
- python3.x 使用http-post方式调用webservice
- java中使用scoket模拟http post请求发送图片或文件