Java调用WebSerivce
起因
一位关系好的前同事问我在Java中如何调用WebService,这位同事一直在做.Net,去年底才开始做Java项目,上手的第一个项目已经是Spring Boot做Web API项目了,所以她本身没有Java项目的经验,所以才想起来问我,有没有调用WebSerivce服务.这事当年还真经历不少.当时是用Axis2生成客户端代码,把代码拷入项目中使用.创建WebSerivce(采用c#创建WebSerivce项目,简单)
using System.Web.Services;
namespace WebService
{
/// <summary>
/// 测试WebSerivce
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
/// <summary>
/// 测试方法1
/// </summary>
/// <returns></returns>
[WebMethod]
public string HelloWorld()
{
return "Hello World11111";
}
/// <summary>
/// 测试方法2 有参数
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
[WebMethod]
public string GetName(string name)
{
return name + "|" + 10;
}
}
}
测试并验证服务是否可以访问.
下载Axis2,并配置Axis2环境变量
下载地址:http://axis.apache.org/axis2/java/core/download.html
将该文件进行解压,并进行到目录中,找到bin,将该路径添加环境变量中,如下图:

# -p指定包名,方便考入到项目 -o可以指定路径,这里没有指定,路径在bin/src
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配置-->
<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重新导入包.
秋风
2020-11-16