前言
- webservice是一个soa架构(即是面向服务的架构),它能够提供基于不同平台,甚至不同语言之间的相互接口调用,c#项目中需要调用java后台提供的一个软件激活码服务,特此学习。
开发服务端
既然是接口调用,则必定有客户端和服务器端。先来看服务端:
1定义接口
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface HelloWorld {
@WebMethod String getResult(String name);
}
- 2接口实现
import javax.jws.WebService;
@WebService(endpointInterface="com.hyq.service.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Override
public String getResult(String name) {
return "你好!"+name;
}
}
- 3.发布服务
public class HelloWorldPublisher {
public static void main(String[] args) {
Endpoint publish = Endpoint.publish("http://localhost:8888/ws/hello", new HelloWorldImpl());
System.out.println(publish);
}
}
- 4.发布服务后,可以通过http://localhost:8888/ws/hello?wsdl访问服务说明文档。
开发客户端
客户端方式1
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8888/ws/hello?wsdl");
QName qName = new QName("http://service.hyq.com/","HelloWorldImplService");
Service service = Service.create(url,qName);
HelloWorld helloWorld = service.getPort(HelloWorld.class);
String result = helloWorld.getResult("小明");
System.out.println(result);
//输出 你好!小明
}
客户端方式2
- 使用wsimport
wsimport -keep -verbose http://localhost:8888/ws/hello?wsdl
生成客户端代码,然后调用
HelloWorldImplService helloService = new HelloWorldImplService();
HelloWorld hello = helloService.getHelloWorldImplPort();
String result = hello.getResult("小明");
System.out.println(result);