在实际系统集成开发的过程中,我们会经常遇到调接口的需求。下面整理了一下两种调webservice(SOAP)的常用代码。
一、基于http和SOAP协议(不用axis和cxf框架)
URL wsUrl = new URL("http://ip:port/servicename.asmx?wsdl");
HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
OutputStream os = conn.getOutputStream();
String temp = "{\"aaa\":\"123\",\"sss\":\"123\"}";
//请求体
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sso=\"http://temp.cn\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<sso:test>"
+ "<sso:info>"+temp+"</sso:info>"
+ "</sso:test>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
os.write(soap.getBytes());
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
String s = "";
while((len = is.read(b)) != -1){
String ss = new String(b,0,len,"UTF-8");
s += ss;
}
System.out.println(s);
is.close();
os.close();
conn.disconnect();
上面的soap内容可以通过SOAPUI工具来生成。到时候拼接即可。这个最大的好处是不需要引入一些框架jar包。
二、基于axis的调用
需引入一些jar包
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.encoding.XMLType;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;
String info1="{\"aaa\":\"111\",\"sss\":\"123\"}";
String ret1 = " ";
try
{
Service service = new Service();
Call call = (Call)service.createCall();
call.setTargetEndpointAddress(new URL("http://ip:port/Service.asmx"));
call.setOperationName(new QName("http://test.cn", "test"));//切忌不是test.cn/
call.addParameter(new QName("http://test.cn", "info"), XMLType.SOAP_STRING, ParameterMode.IN);
call.setReturnType(XMLType.SOAP_STRING);
call.setUseSOAPAction(true);
call.setSOAPActionURI("http://test.cn/" + "test");
try {
ret1 = (String)call.invoke(new Object[] { info1 });
System.out.println(ret1);
if(ret1.equals("")){
ret1=" ";
}
} catch (IOException e) {
ret1 = " ";
e.printStackTrace();
}
}
catch (MalformedURLException e) {
ret1 = " ";
e.printStackTrace();
}
catch (ServiceException e)
{
ret1 = " ";
e.printStackTrace();
}
这样,基本的调用就实现了。
当然,现在流行的调用方式还有基于cxf的调用。此处就不列了。