一.发布webService接口
(1)接口声明
import javax.jws.WebService;
@WebService
public interface Calculator {
String add(String a, String b);
int multi(int a, int b);
}
(2)实现方法
import com.maxnerva.cloud.webservice.service.Calculator;
import javax.jws.WebService;
public class CalculatorImpl implements Calculator {
@Override
public String add(String a, String b) {
return a + b;
}
@Override
public int multi(int a, int b) {
return a * b;
}
}
(3) 发布
public class Test {
public static void main(String[] args) {
Endpoint.publish("http://127.0.0.1:8088/calculator",
new CalculatorImpl());
}
}
二.hutool SoapClient 访问
验证add方法
1.Web 访问:
2.调用
import cn.hutool.http.webservice.SoapClient;
public class TestImpl {
public static void main(String[] args) {
SoapClient soapClient = SoapClient.create("http://127.0.0.1:8088/calculator?wsdl");
soapClient.setMethod("add", "http://service.webservice.cloud.maxnerva.com/").setParam("a", "1").setParam("b","1");
String send = soapClient.send(true);
System.out.println(send);
}
}
3.执行报错: 所需元素为<{}arg1>,<{}arg0>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Unmarshalling Error: 意外的元素 (uri:"http://service.webservice.cloud.maxnerva.com/", local:"a")。所需元素为<{}arg1>,<{}arg0> </faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
三.解决方案
安装SoapUI工具
将测试的webservice 链接加入进去可以看到具体方法体,如图,其中方法名在webService 里面变成了"ser:add";参数变为了"arg0","arg1":
重新修改验证调用方法为:
import cn.hutool.http.webservice.SoapClient;
public class TestImpl {
public static void main(String[] args) {
SoapClient soapClient = SoapClient.create("http://127.0.0.1:8088/calculator?wsdl");
soapClient.setMethod("ser:add", "http://service.webservice.cloud.maxnerva.com/")
.setParam("arg0", "1", false)
.setParam("arg1","1", false);
String send = soapClient.send(true);
System.out.println(send);
}
}
验证结果,成功:
注意参数设置
setParam(String name, Object value, boolean useMethodPrefix) 其中useMethodPrefix为fasle,是不使用方法名的前缀,在这个示例种,方法add的前缀为“ser”
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:addResponse xmlns:ns2="http://service.webservice.cloud.maxnerva.com/">
<return>11</return>
</ns2:addResponse>
</soap:Body>
</soap:Envelope>
四,注意:
使用 @webservic发布webService 接口的时候,方法名或者参数可能和定义有区别,可借助SoapUI工具查看