Java调用webservice的.asmx后缀接口

前两天,在与其他公司做对接中需要回调一个对方的接口,看了文档后发现是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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章