1. 程式人生 > >java 簡單的建立webservice介面 和遠端訪問

java 簡單的建立webservice介面 和遠端訪問

1.使用jdk釋出webservice 

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

/**
 *
 * @author lili
 */
@WebService
public class TestWebService {
    /** 供客戶端呼叫方法  該方法是非靜態的,會被髮布
     * @param name  傳入引數
     * @return  返回結果
     * */
    public String getValue(String name){
        System.out.println("okokokoko: "+name);
        return "hello "+name;
    };
    /**
     * 方法上加@WebMentod(exclude=true)後,此方法不被髮布;
     * @param name
     * @return
     */
    @WebMethod(exclude=true)  
    public String getHello(String name){
        return "你好! "+name;
    }
    /** 靜態方法不會被髮布
     * @param name
     * @return
     */
    public static String getString(String name){
        return "再見!"+name;
    }
    //通過EndPoint(端點服務)釋出一個WebService
    public static void main(String[] args) {
     /*引數:1,本地的服務地址;
           2,提供服務的類;
      */
     Endpoint.publish("http://192.168.1.4:8081/Service/ServiceHello", new TestWebService());
     System.out.println("釋出成功!");
     //釋出成功後 在瀏覽器輸入 http://192.168.1.4:8081/Service/ServiceHello?wsdl
    }
}

 

 

2. java遠端訪問 webservice

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType; 

public static void main(String[] args) {
        try {
            String endpoint = URL;
            // 直接引用遠端的wsdl檔案  
            // 以下都是套路  
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(endpoint);
            call.setOperationName(new QName("http://testwebservice.mycompany.com/","Hello"));// WSDL裡面描述的介面名稱  
            call.addParameter("arg0", XMLType.XSD_DATE,ParameterMode.IN);// 介面的引數  “使用arg0” 服務端才能接收到資料
            call.setReturnType(XMLType.XSD_STRING);// 設定返回型別  
            String temp = "ddd"; //訪問資料
            String result = (String) call.invoke(new Object[]{temp});
            // 給方法傳遞引數,並且呼叫方法  
            System.out.println("result is " + result);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        return "";
    }