使用Java开发一个非常简单的Web Service例子

1.定义一个Web Service 的接口类

package org.yang.ws;

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 TimeServer
{
	@WebMethod
	public String getTimeAsString();
	public long getTimeAsElapsed();
}

2.定义一个Web Service接口的实现类:

package org.yang.ws;

import java.util.Date;

import javax.jws.WebService;

@WebService(endpointInterface="org.yang.ws.TimeServer")
public class TimeServerImpl implements TimeServer
{

	public String getTimeAsString()
	{
		return new Date().toString();
	}

	public long getTimeAsElapsed()
	{
		return new Date().getTime();
	}

}

3.发布Web Service

package org.yang.ws;

import javax.xml.ws.Endpoint;

public class Publisher
{
	public static void main(String[] args)
	{
		Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());
		System.out.println("successfully!!");
	}
}

4.模拟客户发送请求:

package org.yang.ws;

import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

public class Test
{
	public static void main(String[] args) throws Exception
	{
		URL url = new URL("http://127.0.0.1:9876/ts?wsdl");
		QName qName = new QName("http://ws.yang.org/", "TimeServerImplService");
		
		Service service = Service.create(url, qName);
		
		TimeServer eif = service.getPort(TimeServer.class);
		System.out.println(eif.getTimeAsString());
		System.out.println(eif.getTimeAsElapsed());
	}
}

5.以wsdl文档生成的代码来调用:

(1)使用wsimport 命令来将wsdl文档客户端代码:

wsimport -p ts -keep http://127.0.0.1:9876/ts?wsdl

(2)调用服务:

package ts;

public class Test
{
	public static void main(String[] args) throws Exception
	{
			TimeServerImplService service = new TimeServerImplService();
			TimeServer eif = service.getTimeServerImplPort();
			System.out.println(eif.getTimeAsString());
			System.out.println(eif.getTimeAsElapsed());
	}
}



你可能感兴趣的:(使用Java开发一个非常简单的Web Service例子)