WSDL WebService的建立和使用執行個體

來源:互聯網
上載者:User

標籤:

一. WSDL WebService的建立:
1.建立【Web Service Project】:


WebServices Framework要選JAX-WS:


2.寫一個簡單的測試案例:

package com.webservice;public class WebService{public String printData(String printerName){String strRet = "Welcome to use WebService, " + printerName;System.out.println("Print from WebService:" + strRet);return strRet;}}

3.發布Web Service:
點擊工具列的New Web Service:


Strategy選擇第二個(Create web service from Java class):


勾選【Generate WSDL in project】:


點擊【Finish】後,系統會在WEB-INF/wsdl下產生兩個檔案:


WebServiceService.wsdl:這個檔案是用來描述Web Service內容的
<?xml version="1.0" encoding="UTF-8"?><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.3-hudson-390-. --><definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://webservice.com/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="WebServiceService" targetNamespace="http://webservice.com/">  <types>    <xsd:schema>      <xsd:import namespace="http://webservice.com/" schemaLocation="WebServiceService_schema1.xsd"/>    </xsd:schema>  </types>  <message name="printData">    <part element="tns:printData" name="parameters"/>  </message>  <message name="printDataResponse">    <part element="tns:printDataResponse" name="parameters"/>  </message>  <portType name="WebServiceDelegate">    <operation name="printData">      <input message="tns:printData"/>      <output message="tns:printDataResponse"/>    </operation>  </portType>  <binding name="WebServicePortBinding" type="tns:WebServiceDelegate">    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>    <operation name="printData">      <soap:operation soapAction=""/>      <input>        <soap:body use="literal"/>      </input>      <output>        <soap:body use="literal"/>      </output>    </operation>  </binding>  <service name="WebServiceService">    <port binding="tns:WebServicePortBinding" name="WebServicePort">      <soap:address location="http://localhost:8080/WebService/WebServicePort"/>    </port>  </service></definitions>

WebServiceService_schema1.xsd:用來說明Web Service的命令及其參數
比如:sample裡面的WebService是【printData】,有一個String類型的參數【arg0】,返回值一個String類型的值。
<?xml version="1.0" encoding="UTF-8"?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://webservice.com/" targetNamespace="http://webservice.com/" version="1.0">  <xs:element name="printData" type="tns:printData"/>  <xs:element name="printDataResponse" type="tns:printDataResponse"/>  <xs:complexType name="printData">    <xs:sequence>      <xs:element minOccurs="0" name="arg0" type="xs:string"/>    </xs:sequence>  </xs:complexType>  <xs:complexType name="printDataResponse">    <xs:sequence>      <xs:element minOccurs="0" name="return" type="xs:string"/>    </xs:sequence>  </xs:complexType></xs:schema>

將WebService項目部署到Tomcat即可。
(部署方法略)

二. WSDL WebService的調用:
方法1:建立Web Service Client來調用:
1.建立【Java Project】:


2.點擊工具列的New Web Service Client:




3.選擇【WSDL URL】:


4.點擊【Next】完成建立後,在src/com/webservice下,自動產生相關檔案。(WebServiceTest.java除外,這個是自己建立的調用檔案)


5.建立【WebServiceTest.java】


代碼如下:
package com.webservice;public class WebServiceTest{public static void main(String[] args){WebServiceService wssPrintData = new WebServiceService();WebServiceDelegate wsdPrintData = wssPrintData.getWebServicePort();System.out.println(wsdPrintData.printData("sun"));}}

6.【WebServiceTest.java】右鍵→Run As→Java Application
輸出結果:
Welcome to use WebService, sun


方法2:用HttpClient調用:
package com.httpclientforwsdl;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.InputStreamRequestEntity;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.RequestEntity;public class WebServiceHttpClientTest{public synchronized static String accessService(String wsdl,String ns,String method,Map<String,String> params,String result)throws Exception{          //拼接參數          String param = getParam(params);          String soapResponseData = "";          //拼接SOAP          StringBuffer soapRequestData = new StringBuffer("");          soapRequestData.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");          soapRequestData.append("<soap:Body>");          soapRequestData.append("<ns1:"+method+" xmlns:ns1=\""+ns+"\">");          soapRequestData.append(param);          soapRequestData.append("</ns1:"+method+">");          soapRequestData.append("</soap:Body>" + "</soap:Envelope>");          PostMethod postMethod = new PostMethod(wsdl);          // 然後把Soap請求資料添加到PostMethod中          byte[] b=null;          InputStream is=null;          try {              b = soapRequestData.toString().getBytes("utf-8");               is = new ByteArrayInputStream(b, 0, b.length);              RequestEntity re = new InputStreamRequestEntity(is, b.length,"text/xml; charset=UTF-8");              postMethod.setRequestEntity(re);              HttpClient httpClient = new HttpClient();              int status = httpClient.executeMethod(postMethod);              System.out.println("status:"+status);              if(status==200){                  soapResponseData = getMesage(postMethod.getResponseBodyAsString(),result);              }          } catch (Exception e) {              e.printStackTrace();          } finally{              if(is!=null){                  is.close();              }          }          return soapResponseData;      }            public static String getParam(Map<String,String> params){          String param = "";          if(params!=null){              Iterator<String> it  = params.keySet().iterator();              while(it.hasNext()){                  String str = it.next();                  param+="<"+str+">";                  param+=params.get(str);                  param+="</"+str+">";              }          }          return param;      }            public static String getMesage(String soapAttachment,String result){          System.out.println("message:"+soapAttachment);          if(result==null){              return null;          }          if(soapAttachment!=null && soapAttachment.length()>0){              int begin = soapAttachment.indexOf(result);              begin = soapAttachment.indexOf(">", begin);              int end = soapAttachment.indexOf("</"+result+">");              String str = soapAttachment.substring(begin+1, end);              str = str.replaceAll("<", "<");              str = str.replaceAll(">", ">");              return str;          }else{              return "";          }      }            /**      * @param args      */      public static void main(String[] args) {           try {              Map<String,String> param = new HashMap<String,String>();              param.put("arg0", "sun");            String wsdl="http://localhost:8080/WebService/WebServicePort?wsdl";              String ns = "http://webservice.com/";              String method="printData";              String response =accessService(wsdl,ns,method,param,"return");              System.out.println("main:"+response);                        } catch (Exception e) {              e.printStackTrace();          }      }  }

顯示結果:
status:200七月 15, 2016 3:43:27 下午 org.apache.commons.httpclient.HttpMethodBase getResponseBody警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.message:<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:printDataResponse xmlns:ns2="http://webservice.com/"><return>Welcome to use WebService, sun</return></ns2:printDataResponse></S:Body></S:Envelope>main:Welcome to use WebService, sun

WSDL WebService和RestFul WebService的個人理解:

RestFul WebService的建立和使用執行個體:

http://blog.csdn.net/sunroyi666/article/details/51918675

WSDL WebService和RestFul WebService的Sample代碼:
http://download.csdn.net/detail/sunroyi666/9577143

WSDL WebService的建立和使用執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.