使用http的方式访问webService接口
在工作中遇到的第一个难题 以前自己从来没有研究过,所以记录下来。
1. 使用接口访问工具测试接口是否可以正常访问
2. 了解访问接口的必备属性 wsdl 路径;namespace 命名空间 ;method 方法 ;str 入参。
3. 通过调试工具,获取到访问接口的入参和出参的xml
完成以上工作 我们可以开始coding啦 因为我的访问接口的入参出参 是用json格式的。大家可以根据自己入参出参进行改造。
1.访问接口的工具类
/**
* 访问服务
*
* @param wsdl wsdl地址
* @param ns 命名空间
* @param method 方法名
* @param list 参数
* @throws Exception
*/
public synchronized static String accessService(String wsdl, String ns, String method, String jsonStr) throws Exception {
String soapResponseData = "";
//拼接SOAP
StringBuffer soapRequestData = new StringBuffer("");
soapRequestData.append( "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://service.webservice.web.infotrust.com\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
soapRequestData.append("<soapenv:Body>");
soapRequestData.append("<q0:" + method + ">");
soapRequestData.append("<q0:in0>"+jsonStr+"</q0:in0> ");
soapRequestData.append("</q0:" + method + ">");
soapRequestData.append("</soapenv:Body>" + "</soapenv:Envelope>");
PostMethod postMethod = new PostMethod(wsdl);
// 然后把Soap请求数据添加到PostMethod中
byte[] b = null;
InputStream is = null;
try {
b = soapRequestData.toString().getBytes("utf-8");
is = new ByteArrayInputStream(b, 0, b.length);
RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=UTF-8");
postMethod.setRequestEntity(re);
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10*60*1000); //设置连接超时时间
httpClient.getHttpConnectionManager().getParams().setSoTimeout(10*60*1000);//设置读取超时时间
int status = httpClient.executeMethod(postMethod);
if (status == 200) {
soapResponseData = getMesage(postMethod.getResponseBodyAsString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
}
return soapResponseData;
}
2.解析出参的工具类
/**
* 解析参数
* @throws Exception
*/
public static String getMesage(String soapAttachment) throws Exception {
if (soapAttachment != null && soapAttachment.length() > 0) {
Document document=null;
document=DocumentHelper.parseText(soapAttachment);
//获取根元素
Element root=document.getRootElement();
//获取根元素下的所有子元素
List<Element> list=root.elements();
list=list.get(0).elements();
String str = list.get(0).elementTextTrim("out");
return str;
} else {
return "";
}
}
然后任务完成啦~
这篇博客记录了在工作中使用HTTP方式访问WebService接口的全过程,包括测试接口、理解必备属性如WSDL路径、命名空间和方法,以及如何处理JSON格式的入参和出参。博主分享了访问接口的工具类和出参解析工具类的使用。
2164





