webservice 接口调用方式有很多。项目中用到的是海康视频平台视频的获取;
- soap+xml 格式 (xml请求数据解析性能问题)、
- jdk自带的wsimport 实现如调用本地接口一样实现远程接口的调用 (灵活性不足)
- cxf包中提供的 JaxWsDynamicClientFactory 类调用 (可能会存在JAR冲突问题)
- Ajax调用方式(存在跨域问题)
本文实现的是Soap+xml调用方式。
话不多说,上代码。后面陆续把其他调用方式做一整理。
public class SOAPUtil {
private static int socketTimeout = 30000;// 请求超时时间
private static int connectTimeout = 30000;// 传输超时时间
/**
* 访问webservice接口
* @param namespace 命名空间
* @param postUrl webservice接口地址
* @param soapAction soapAction地址
* @param method 方法名
* @param paramsNum 参数个数
* @param params 参数组
* @return 返回值
*/
public static String execute(String namespace,String postUrl,String soapAction,String method,int paramsNum,Object[] params){
StringBuffer sb=new StringBuffer("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"");
sb.append(namespace);
sb.append("\"><soapenv:Header/><soapenv:Body><com:");
sb.append(method);
sb.append(">");
for (int i = 0; i < paramsNum; i++) {
sb.append("<com:in"+i+">"+params[i]+"</com:in"+i+">");
}
sb.append("</com:");
sb.append(method);
sb.append("></soapenv:Body></soapenv:Envelope>");
String result=doPostSoap1_1(postUrl, sb.toString(), soapAction);
//去掉转义字符
String xml = StringEscapeUtils.unescapeHtml4(result);
//获取返回结果
xml = xml.substring(xml.indexOf("<ns:return>")+"<ns:return>".length(),xml.indexOf("</ns:return>"));
return xml;
}
/**
* 使用SOAP1.1发送消息
*
* @param postUrl
* @param soapXml
* @param soapAction
* @return
*/
public static String doPostSoap1_1(String postUrl, String soapXml,
String soapAction) {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
try {
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", soapAction);
StringEntity data = new StringEntity(soapXml,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
}
return retStr;
}
/**
* 使用SOAP1.2发送消息
*
* @param postUrl
* @param soapXml
* @param soapAction
* @return
*/
public static String doPostSoap1_2(String postUrl, String soapXml,String soapAction) {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
try {
httpPost.setHeader("Content-Type",
"application/soap+xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", soapAction);
StringEntity data = new StringEntity(soapXml,Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
}
return retStr;
}
/**
* @description 将xml字符串转换成List<map>
* @param xml
* @return Map
*/
public static List<Map<String, Object>> readStringXmlOut(String xml) {
Document doc = null;
List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
try {
// 将字符串转为XML
doc = DocumentHelper.parseText(xml);
// 获取根节点
Element rootElt = doc.getRootElement();
// 获取根节点下的子节点rows
Iterator iter = rootElt.elementIterator("rows");
// 遍历rows节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
// 获取子节点head下的子节点row
Iterator iters = recordEle.elementIterator("row");
// 遍历rows节点下的row节点
while (iters.hasNext()) {
Element itemEle = (Element) iters.next();
String tgt = itemEle.attributeValue("tgt");
String st = itemEle.attributeValue("st");
String c_device_ip = itemEle.attributeValue("c_device_ip");
String c_index_code = itemEle.attributeValue("c_index_code");
Map<String, Object> map = new HashMap<String, Object>();
map.put("tgt", tgt);
map.put("st", st);
map.put("c_device_ip", c_device_ip);
map.put("c_index_code", c_index_code);
listMap.add(map);
}
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return listMap;
}
文中涉及的包如下:
import java.nio.charset.Charset;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;