起因
一位关系好的前同事问我在Java中如何调用WebService,这位同事一直在做.Net,去年底才开始做Java项目,上手的第一个项目已经是Spring Boot做Web API项目了,所以她本身没有Java项目的经验,所以才想起来问我,有没有调用WebSerivce服务.这事当年还真经历不少.当时是用Axis2生成客户端代码,把代码拷入项目中使用.
创建WebSerivce(采用c#创建WebSerivce项目,简单)
using System.Web.Services;
namespace WebService
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World11111";
}
[WebMethod]
public string GetName(string name)
{
return name + "|" + 10;
}
}
}
测试并验证服务是否可以访问.
下载Axis2,并配置Axis2环境变量
下载地址:
http://axis.apache.org/axis2/java/core/download.html将该文件进行解压,并进行到目录中,找到bin,将该路径添加环境变量中,如下图:
wsdl2java -uri http://localhost:50309/WebService1.asmx?wsdl -p qiufeng.webservice
将生成代码,拷入项目中,
public static void main(String[] args) throws IOException {
WebService1Stub service = new WebService1Stub();
WebService1Stub.HelloWorld hello = new WebService1Stub.HelloWorld();
WebService1Stub.HelloWorldResponse response = service.helloWorld(hello);
String result = response.getHelloWorldResult();
System.out.println(result);
WebService1Stub.GetName getName = new WebService1Stub.GetName();
getName.setName("hello");
WebService1Stub.GetNameResponse response1 = service.getName(getName);
String name = response1.getGetNameResult();
System.out.println(name);
}
修改pom.xml,加入axis2所需的依赖包:
<properties>
<java.version>1.8</java.version>
<axis2.version>1.7.9</axis2.version>
</properties>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-spring</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-http</artifactId>
<version>${axis2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-local</artifactId>
<version>${axis2.version}</version>
</dependency>
让Maven重新导入包.