调用webService的几种方式
方式一(比较通用):
//webService地址
String url = "xxxx/xxxService?wsdl";
//创建一个service
Service service = new Service();
//创建一个Call对象
Call call = (Call) service.createCall();
//设置地址
call.setTargetEndpointAddress(url);
//WSDL里面描述的接口名
call.setOperationName("queryPlan");
//访问接口参数和参数类型及参数模型IN, OUT or INOUT(params为参数List<Map<String,Object>> params = new ArrayList<>();)
Object[] obj = new Object[params.size()];
for (int i = 0; i < params.size(); i++) {
Map<String, Object> map = params.get(i);
call.addParameter( map.get("paramName"), map.get("paramType"),
ParameterMode.IN);
obj[i] = map.get("paramValue");
}
//设置返回值类型
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
String response = (String) call.invoke(new Object[]{stCompanyCode});
System.out.println("response = " + response);
方式二:
LinkedHashMap<String, Object> params = new LinkedHashMap<>();
String url = "xxxx/xxxService?wsdl";
String request1 = RestClientM2T3.doWsdlRequest(url, "queryPlan", params);
Document document = DocumentHelper.parseText(request1);
Node result = document.selectSingleNode("/soap:Envelope//return");
JSONArray json = JSONArray.fromObject(result.getText());
System.out.println("response = " + json.toString());
public static String doWsdlRequest(String url1,String method, LinkedHashMap<String, Object> params) throws Exception {
HttpClient httpclient = getHttpClient(BASE_URL.startsWith("https://"));
HttpPost httpPost = new HttpPost(BASE_URL);
String content = APP_ID + url1+ System.currentTimeMillis() / 1000;
String signature = encrypt(content);
httpPost.addHeader("appid", APP_ID);
httpPost.addHeader("apiname", url1);
httpPost.addHeader("signature", signature);
if (params!=null) {
StringBuffer xml = new StringBuffer("");
xml.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:your=\"http://yourcompany.com/\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <your:"+method+">\n");
int index= 0;
for (Map.Entry<String, Object> entry : params.entrySet()) {
String paramValue = entry.getValue()==null?"": entry.getValue().toString();
xml.append("<arg"+index +">"+paramValue+"</arg"+index +">\n");
index++;
}
xml.append("</your:"+method+">\n");
xml.append("</soapenv:Body>\n");
xml.append("</soapenv:Envelope>\n");
httpPost.setEntity(new StringEntity(xml.toString(), Charset.forName("UTF-8")));
}
httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
byte[] bytes = toByteArray(is);
is.close();
String s = new String(bytes, "UTF-8");
StatusLine statusLine = httpResponse.getStatusLine();
httpPost.releaseConnection();
if (statusLine.getStatusCode() == 200) {
System.out.println(s);
return s;
} else {
System.out.println(statusLine.getStatusCode() + ":" + statusLine.getReasonPhrase());
throw new RuntimeException(s);
}
return null;
}