web service 的跨语言特性
1.用java语言创建一个的服务(Myservice)
①编写一个Imyservice接口(注解不能少)
@WebService public interface Imyservice { public int add(int a,int b); public int minus(int a,int b); }
②编写Imyservice接口的实现类ImyserviceImpl(注解不能少)
@WebService(endpointInterface="com.myservice.Imyservice") public class MyserviceImpl implements Imyservice { @Override public int add(int a, int b) { System.out.println(a+"+"+b+"="+(a+b)); return a+b; } @Override public int minus(int a, int b) { System.out.println(a+"-"+b+"="+(a-b)); return a-b; } }
③编写主函数Myservice,发布编写的服务
public class Myservice { public static void main(String[] args) { String address="http://localhost:8888/ns"; Endpoint.publish(address, new MyserviceImpl()); } }
④运行java程序,发布服务,然后在浏览器地址栏输入http://localhost:8888/ns
2.调用此服务(保持服务开启)
①用java语言调用
public class TestClient { public static void main(String[] args) { try { URL url = new URL("http://localhost:8888/ns?wsdl"); QName name=new QName("http://myservice.com/", "MyserviceImplService"); Service service=Service.create(url, name); Imyservice ms=service.getPort(Imyservice.class); System.out.println(ms.add(34, 23)); } catch (MalformedURLException e) { e.printStackTrace(); } } }
②用C#语言调用
(1)打开Microsoft Visual Studio 2013,新创一个工程叫JavaWebService建完后,查看解决方案资源管理器,右键引用,“增加服务引用”会出现添加Web引用的向导,在url里面填入wsdl的URL,并命名为JavaService。直接点下源代码,首先得导入命名空间:using JavaWebServices.JavaService;
(2)然后输入如下代码:
using System.Threading.Tasks; using JAVAWebServices.JavaService; namespace JAVAWebServices { class Program { static void Main(string[] args) { JavaService.ImyserviceClient userServices = new ImyserviceClient(); int result=userServices.add(2, 3); int result2 = userServices.minus(3,2); Console.WriteLine(result); Console.WriteLine(result2); Console.ReadLine(); } } }
(3)运行程序就可得到想要的结果,并且在java服务端的后台可以看到打印的内容