关闭

基于java 使用http-post方式请求https webservice接口

标签: web servicejavahttpshttppost
503人阅读 评论(0) 收藏 举报
分类:

本文章记录请求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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:637次
    • 积分:27
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档