【轉(zhuǎn)】java 實(shí)現(xiàn)WebService 以及不同的調(diào)用方式

webservice:
就是應(yīng)用程序之間跨語(yǔ)言的調(diào)用
wwww.webxml.com.cn

  • 1.xml
    1. wsdl: webservice description language web服務(wù)描述語(yǔ)言
      通過(guò)xml格式說(shuō)明調(diào)用的地址方法如何調(diào)用,可以看webservice的說(shuō)明書
  • 3.soap simple object access protoacl (簡(jiǎn)單對(duì)象訪問(wèn)協(xié)議)
    限定了xml的格式
    soap 在http(因?yàn)橛姓?qǐng)求體,所以必須是post請(qǐng)求)的基礎(chǔ)上傳輸xml數(shù)據(jù)
    請(qǐng)求和響應(yīng)的xml 的格式如:
  <Envelop>
     <body>
               //....
     </body>
  </Envelop>

operation name:服務(wù)提供的方法
靜態(tài)方法不能發(fā)布為外部服務(wù)

運(yùn)用jkd自帶的代碼生成訪問(wèn)服務(wù)器的客戶端代碼 E:/wsimort -s . http://test.cm/?wsdl

我們可以把webservice看做是web服務(wù)器上的一個(gè)應(yīng)用,web服務(wù)器是webservice的一個(gè)容器

函數(shù)的參數(shù)在 http://test.cm/?xsd=1

JAX-WS是指 java api for xml -WebService

//測(cè)試 WebService服務(wù)的 explorer
Web Service Explorer 可以顯示返回的xml格式

targetNamespace 默認(rèn)為倒置的包名

客戶端調(diào)用WebService的方式:

  • 1.通過(guò)wximport生成代碼
  • 2.通過(guò)客戶端編程方式
  • 3.通過(guò)ajax調(diào)用方式
  • 4.通過(guò) URL Connection 方式調(diào)用

請(qǐng)求過(guò)程分析:

  • 1.使用get方式獲取wsdl文件,稱為握手
  • 2.使用post發(fā)出請(qǐng)求
  • 3.服務(wù)器響應(yīng)成功過(guò)

幾種監(jiān)聽(tīng)工具:

  • http watch
  • Web Service explorer
  • eclipse 自帶工具
  • TCP/IP Monitor

服務(wù)端代碼:

import javax.jws.WebMethod;  
import javax.jws.WebParam;  
import javax.jws.WebResult;  
import javax.jws.WebService;  
import javax.xml.ws.Endpoint;  
  
/** 
 * WebService 
 * 將 Java 類標(biāo)記為實(shí)現(xiàn) Web Service,或者將 Java 接口標(biāo)記為定義 Web Service 接口 
 */  
@WebService(serviceName="MyService",targetNamespace="http://www.baidu.com")  
public class HelloService {  
      
    @WebMethod(operationName="AliassayHello")  
    @WebResult(name="myReturn")  
    public String sayHello(@WebParam(name="name") String name){  
        return  "hello: " + name;  
    }  
      
    public String sayGoodbye(String name){  
      
        return  "goodbye: " + name;  
    }  
      
    @WebMethod(exclude=true)//當(dāng)前方法不被發(fā)布出去  
    public String sayHello2(String name){  
        return "hello " + name;  
    }  
  
    public static void main(String[] args) {  
        /** 
         * 參數(shù)1:服務(wù)的發(fā)布地址 
         * 參數(shù)2:服務(wù)的實(shí)現(xiàn)者 
         *  Endpoint  會(huì)重新啟動(dòng)一個(gè)線程 
         */  
        Endpoint.publish("http://test.cm/", new HelloService());  
        System.out.println("Server ready...");  
    }  
}

1.客戶端調(diào)用(wximport自動(dòng)生成代碼 【推薦】)

public class App {  
  
    /** 
     * 通過(guò)wsimport 解析wsdl生成客戶端代碼調(diào)用WebService服務(wù) 
     *  
     * @param args 
     *  
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
          
        /** 
         * <service name="MyService"> 
         * 獲得服務(wù)名稱 
         */  
        MyService mywebService = new MyService();  
          
        /** 
         * <port name="HelloServicePort" binding="tns:HelloServicePortBinding"> 
         */  
        HelloService hs = mywebService.getHelloServicePort();  
          
        /** 
         * 調(diào)用方法 
         */  
        System.out.println(hs.sayGoodbye("sjk"));  
          
        System.out.println(hs.aliassayHello("sjk"));  
          
          
          
    }  
  
}

2.通過(guò)ajax+js+xml調(diào)用

    <html>  
        <head>  
            <title>通過(guò)ajax調(diào)用WebService服務(wù)</title>  
            <script>  
                  
                var xhr = new ActiveXObject("Microsoft.XMLHTTP");  
                function sendMsg(){  
                    var name = document.getElementById('name').value;  
                    //服務(wù)的地址  
                    var wsUrl = 'http://192.168.1.100:6789/hello';  
                      
                    //請(qǐng)求體  
                    var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.itcast.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +   
                                         ' <soapenv:Body> <q0:sayHello><arg0>'+name+'</arg0>  </q0:sayHello> </soapenv:Body> </soapenv:Envelope>';  
                                           
                    //打開(kāi)連接  
                    xhr.open('POST',wsUrl,true);  
                      
                    //重新設(shè)置請(qǐng)求頭  
                    xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8");  
                      
                    //設(shè)置回調(diào)函數(shù)  
                    xhr.onreadystatechange = _back;  
                      
                    //發(fā)送請(qǐng)求  
                    xhr.send(soap);  
                }  
                  
                function _back(){  
                    if(xhr.readyState == 4){  
                        if(xhr.status == 200){  
                                //alert('調(diào)用Webservice成功了');  
                                var ret = xhr.responseXML;  
                                var msg = ret.getElementsByTagName('return')[0];  
                                document.getElementById('showInfo').innerHTML = msg.text;  
                                //alert(msg.text);  
                            }  
                    }  
                }  
            </script>  
        </head>  
        <body>  
                <input type="button" value="發(fā)送SOAP請(qǐng)求" onclick="sendMsg();">  
                <input type="text" id="name">  
                <div id="showInfo">  
                </div>  
        </body>  
    </html>  

3.URL Connection方式

    import java.io.InputStream;  
    import java.io.OutputStream;  
    import java.net.HttpURLConnection;  
    import java.net.URL;  
    /** 
     * 通過(guò)UrlConnection調(diào)用Webservice服務(wù) 
     * 
     */  
    public class App {  
      
        public static void main(String[] args) throws Exception {  
            //服務(wù)的地址  
            URL wsUrl = new URL("http://192.168.1.100:6789/hello");  
              
            HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();  
              
            conn.setDoInput(true);  
            conn.setDoOutput(true);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");  
              
            OutputStream os = conn.getOutputStream();  
              
            //請(qǐng)求體  
            String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:q0=\"http://ws.itcast.cn/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +   
                          "<soapenv:Body> <q0:sayHello><arg0>aaa</arg0>  </q0:sayHello> </soapenv:Body> </soapenv:Envelope>";  
              
            os.write(soap.getBytes());  
              
            InputStream is = conn.getInputStream();  
              
            byte[] b = new byte[1024];  
            int len = 0;  
            String s = "";  
            while((len = is.read(b)) != -1){  
                String ss = new String(b,0,len,"UTF-8");  
                s += ss;  
            }  
            System.out.println(s);  
              
            is.close();  
            os.close();  
            conn.disconnect();  
        }  
    }  

4.客戶端編程方式(和第一種方式一樣)

    //文件名:HelloService.java  
      
    import javax.jws.WebMethod;  
    import javax.jws.WebParam;  
    import javax.jws.WebResult;  
    import javax.jws.WebService;  
    import javax.xml.bind.annotation.XmlSeeAlso;  
    import javax.xml.ws.RequestWrapper;  
    import javax.xml.ws.ResponseWrapper;  
      
      
    /** 
     * This class was generated by the JAX-WS RI. 
     * JAX-WS RI 2.1.6 in JDK 6 
     * Generated source version: 2.1 
     *  
     */  
    @WebService(name = "HelloService", targetNamespace = "http://ws.itcast.cn/")  
    @XmlSeeAlso({  
          
    })  
    public interface HelloService {  
      
      
        /** 
         *  
         * @param arg0 
         * @return 
         *     returns java.lang.String 
         */  
        @WebMethod  
        @WebResult(targetNamespace = "")  
        @RequestWrapper(localName = "sayHello", targetNamespace = "http://ws.itcast.cn/", className = "cn.itcast.ws.client.SayHello")  
        @ResponseWrapper(localName = "sayHelloResponse", targetNamespace = "http://ws.itcast.cn/", className = "cn.itcast.ws.client.SayHelloResponse")  
        public String sayHello(  
            @WebParam(name = "arg0", targetNamespace = "")  
            String arg0);  
      
    }  
    import java.net.MalformedURLException;  
    import java.net.URL;  
      
    import javax.xml.namespace.QName;  
    import javax.xml.ws.Service;  
      
    import cn.itcast.ws.wsimport.HelloService;  
      
    /** 
     * 通過(guò)客戶端編程的方式調(diào)用Webservice服務(wù) 
     * 
     */  
    public class App {  
      
        public static void main(String[] args) throws Exception {  
            URL wsdlUrl = new URL("http://192.168.1.100:6789/hello?wsdl");  
            Service s = Service.create(wsdlUrl, new QName("http://ws.itcast.cn/","HelloServiceService"));  
            HelloService hs = s.getPort(new QName("http://ws.itcast.cn/","HelloServicePort"), HelloService.class);  
            String ret = hs.sayHello("zhangsan");  
            System.out.println(ret);  
        }  
    }  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,839評(píng)論 18 399
  • 一、Java基礎(chǔ) 1.寫出下面代碼的執(zhí)行結(jié)果 2.寫出下面代碼的執(zhí)行結(jié)果 3.寫出下面代碼的執(zhí)行結(jié)果 (此題需寫出...
    joshul閱讀 577評(píng)論 0 1
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • 概覽 CXF frontends 是一組編程的API,被用來(lái)開(kāi)發(fā)和發(fā)布webservice。CXF支持兩種類型的f...
    JohnShen閱讀 1,478評(píng)論 2 2
  • 最近小編看到有讀者留言,說(shuō)自己跑了快一個(gè)月了,可是體重不僅沒(méi)有減下去,反而相比起以前還長(zhǎng)了幾斤肉。為了跑了怎么久都...
    水墨無(wú)痕1閱讀 520評(píng)論 0 7

友情鏈接更多精彩內(nèi)容