使用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());
	}
}



發佈了212 篇原創文章 · 獲贊 71 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章