前兩天,在與其他公司做對接中需要回調一個對方的接口,看了文檔後發現是webservice的接口,而且接口名後面還有.asmx的後綴,因爲之前接觸的webservice接口都是wsdl的形式,所以立馬網上搜尋一番,在此記錄下具體實現。
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
public class WebUtil {
public static final String url = "http://127.0.0.1/ToVideoWebService.asmx";
public static void main(String[] args){
Object[] params = new Object[]{"stryang",18};
String result = sendWebservice(url, params);
System.out.println(result);
}
public static String sendWebservice(Object[] params, String url) {
String soapaction = "http://tempuri.org/"; // 域名,這是在server定義的
String operationName = "VideoWebService";// 調用方法名
Service service = new Service();
String ret = "";
try {
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(url);
call.setOperationName(new QName(soapaction, operationName)); // 設置要調用哪個方法
call.addParameter(new QName(soapaction, "name"), // 設置要傳遞的參數
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.addParameter(new QName(soapaction, "age"), // 設置要傳遞的參數
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// (標準的類型)
call.setUseSOAPAction(true);
call.setSOAPActionURI(soapaction + operationName);
ret = (String) call.invoke(params);// 調用方法並傳遞參數
} catch (Exception ex) {
ex.printStackTrace();
}
return ret;
}
}
調用域名及調用方法名是在server端SOAPAction配置
POST /test/ToVideoWebService.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/VideoWebService"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<VideoWebService xmlns="http://tempuri.org/">
<name>string</name>
<age>int</age>
</VideoWebService>
</soap:Body>
</soap:Envelope>
該配置可在web頁面查看
http://服務器ip+端口(默認80,可不填)/部署項目名/接口名(.asmx)