java調用webservice的四種方式,javawebservice

來源:互聯網
上載者:User

java調用webservice的四種方式,javawebservice
webservice:
    就是應用程式之間跨語言的調用
    wwww.webxml.com.cn
    1.xml
    2.    wsdl: webservice description language web服務描述語言
        通過xml格式說明調用的地址方法如何調用,可以看錯webservice的說明書
    
    3.soap simple object access protoacl (簡易物件存取通訊協定 (SOAP))
        限定了xml的格式
        soap 在http(因為有請求體,所以必須是post請求)的基礎上傳輸xml資料
            請求和響應的xml 的格式如:    <Envelop>
                                <body>
                                //....
                                </body>
                            </Envelop>
                operation name:服務提供的方法
                
        
    靜態方法不能發布為外部服務
    
    運用jkd內建的代碼產生訪問伺服器的用戶端代碼    E:/wsimort -s . http://test.cm/?wsdl
    
    我們可以把webservice看做是web伺服器上的一個應用,web伺服器是webservice的一個容器
    
    函數的參數在 http://test.cm/?xsd=1
    
    JAX-WS是指 java api for xml -WebService
    
    //測試 WebService服務的 explorer
    Web Service Explorer 可以顯示返回的xml格式
    
    targetNamespace 預設為倒置的包名
    
用戶端調用WebService的方式:
    1.通過wximport產生代碼
    2.通過用戶端編程方式
    3.通過ajax調用方式
    4.通過 URL Connection 方式調用


請求過程分析:
        1.使用get方式擷取wsdl檔案,稱為握手
        2.使用post發出請求

        3.伺服器響應成功過


幾種監聽工具:
    http watch
    Web Service explorer
    eclipse 內建工具   TCP/IP Monitor


  服務端代碼:

<span style="font-size:18px;">package com.webservcie;import javax.jws.WebMethod;import javax.jws.WebParam;import javax.jws.WebResult;import javax.jws.WebService;import javax.xml.ws.Endpoint;/** * WebService * 將 Java 類標記為實現 Web Service,或者將 Java 介面標記為定義 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)//當前方法不被發布出去    public String sayHello2(String name){        return "hello " + name;    }    public static void main(String[] args) {        /**         * 參數1:服務的發布地址         * 參數2:服務的實現者         *  Endpoint  會重新啟動一個線程         */        Endpoint.publish("http://test.cm/", new HelloService());        System.out.println("Server ready...");    }}</span>

1.用戶端調用(wximport自動產生代碼 【推薦】)

<span style="font-size:18px;">package com.wsclient;public class App {    /**     * 通過wsimport 解析wsdl產生用戶端代碼調用WebService服務     *      * @param args     *      */    public static void main(String[] args) {        // TODO Auto-generated method stub                /**         * <service name="MyService">         * 獲得服務名稱         */        MyService mywebService = new MyService();                /**         * <port name="HelloServicePort" binding="tns:HelloServicePortBinding">         */        HelloService hs = mywebService.getHelloServicePort();                /**         * 調用方法         */        System.out.println(hs.sayGoodbye("sjk"));                System.out.println(hs.aliassayHello("sjk"));                            }}</span>
 2.通過ajax+js+xml調用

<html>    <head>        <title>通過ajax調用WebService服務</title>        <script>                        var xhr = new ActiveXObject("Microsoft.XMLHTTP");            function sendMsg(){                var name = document.getElementById('name').value;                //服務的地址                var wsUrl = 'http://192.168.1.100:6789/hello';                                //請求體                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>';                                                     //開啟串連                xhr.open('POST',wsUrl,true);                                //重新佈建要求頭                xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8");                                //設定回呼函數                xhr.onreadystatechange = _back;                                //發送請求                xhr.send(soap);            }                        function _back(){                if(xhr.readyState == 4){                    if(xhr.status == 200){                            //alert('調用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="發送SOAP請求" 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;/** * 通過UrlConnection調用Webservice服務 * */public class App {    public static void main(String[] args) throws Exception {        //服務的地址        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();                //請求體        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.javaimport 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;/** * 通過用戶端編程的方式調用Webservice服務 * */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);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.