1. 程式人生 > >Java釋出一個簡單webservice應用,併發送SOAP請求

Java釋出一個簡單webservice應用,併發送SOAP請求

一、建立併發佈一個簡單的webservice應用

  1、webservice 程式碼:

複製程式碼
 1 package com.ls.demo;
 2 
 3 import javax.jws.WebMethod;
 4 import javax.jws.WebService;
 5 import javax.xml.ws.Endpoint;
 6 
 7 
 8 @WebService
 9 public class HelloWorld {
10     @WebMethod
11     public String sayHello(String str){
12         System.out.println("get Message...");
13 String result = "Hello World, "+str; 14 return result; 15 } 16 public static void main(String[] args) { 17 System.out.println("server is running"); 18 String address="http://localhost:9000/HelloWorld"; 19 Object implementor =new HelloWorld(); 20 Endpoint.publish(address, implementor);
21 } 22 23 }
複製程式碼

  2、執行專案,並訪問 "http://localhost:9000/HelloWorld?wsdl",得到如下wsdl檔案,說明webservice釋出成功:

複製程式碼
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!-- Published by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. -->
 3 <!--
Generated by JAX-WS RI (http://jax-ws.java.net). RI's version is JAX-WS RI 2.2.9-b130926.1035 svn-revision#5f6196f2b90e9460065a4c2f4e30e065b245e51e. --> 4 <definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://demo.ls.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://demo.ls.com/" name="HelloWorldService"> 5 <types> 6 <xsd:schema> 7 <xsd:import namespace="http://demo.ls.com/" schemaLocation="http://localhost:9000/HelloWorld?xsd=1"></xsd:import> 8 </xsd:schema> 9 </types> 10 <message name="sayHello"> 11 <part name="parameters" element="tns:sayHello"></part> 12 </message> 13 <message name="sayHelloResponse"> 14 <part name="parameters" element="tns:sayHelloResponse"></part> 15 </message> 16 <portType name="HelloWorld"> 17 <operation name="sayHello"> 18 <input wsam:Action="http://demo.ls.com/HelloWorld/sayHelloRequest" message="tns:sayHello"></input> 19 <output wsam:Action="http://demo.ls.com/HelloWorld/sayHelloResponse" message="tns:sayHelloResponse"></output> 20 </operation> 21 </portType> 22 <binding name="HelloWorldPortBinding" type="tns:HelloWorld"> 23 <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"></soap:binding> 24 <operation name="sayHello"> 25 <soap:operation soapAction=""></soap:operation> 26 <input> 27 <soap:body use="literal"></soap:body> 28 </input> 29 <output> 30 <soap:body use="literal"></soap:body> 31 </output> 32 </operation> 33 </binding> 34 <service name="HelloWorldService"> 35 <port name="HelloWorldPort" binding="tns:HelloWorldPortBinding"> 36 <soap:address location="http://localhost:9000/HelloWorld"></soap:address> 37 </port> 38 </service> 39 </definitions>
複製程式碼

二、客戶端訪問webservice

  1、通過 HttpClient 及  HttpURLConnection 傳送SOAP請求,程式碼如下:

複製程式碼
 1 import java.io.BufferedReader;
 2 import java.io.DataOutputStream;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.net.HttpURLConnection;
 6 import java.net.URL;
 7 
 8 import org.apache.commons.httpclient.HttpClient;
 9 import org.apache.commons.httpclient.methods.PostMethod;
10 import org.apache.commons.httpclient.methods.RequestEntity;
11 import org.apache.commons.httpclient.methods.StringRequestEntity;
12 import org.apache.commons.io.IOUtils;
13 
14 public class TestHelloWrold {
15     public static void main(String[] args) throws Exception {
16         String wsdl = "http://localhost:9000/HelloWorld?wsdl";
17         int timeout = 10000;
18         StringBuffer sb = new StringBuffer("");
19         sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
20         sb.append("<soap:Envelope "
21                 + "xmlns:api='http://demo.ls.com/' "
22                 + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
23                 + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
24                 + "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
25         sb.append("<soap:Body>");
26         sb.append("<api:sayHello>");
27         sb.append("<arg0>ls</arg0>");
28         sb.append("</api:sayHello>");
29         sb.append("</soap:Body>");
30         sb.append("</soap:Envelope>");
31 
32         
33         
34         // HttpClient傳送SOAP請求
35         System.out.println("HttpClient 傳送SOAP請求");
36         HttpClient client = new HttpClient();
37         PostMethod postMethod = new PostMethod(wsdl);
38         // 設定連線超時
39         client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
40         // 設定讀取時間超時
41         client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
42         // 然後把Soap請求資料新增到PostMethod中
43         RequestEntity requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
44         //設定請求頭部,否則可能會報 “no SOAPAction header” 的錯誤
45         postMethod.setRequestHeader("SOAPAction","");
46         // 設定請求體
47         postMethod.setRequestEntity(requestEntity);
48         int status = client.executeMethod(postMethod);
49         // 列印請求狀態碼
50         System.out.println("status:" + status);
51         // 獲取響應體輸入流
52         InputStream is = postMethod.getResponseBodyAsStream();
53         // 獲取請求結果字串
54         String result = IOUtils.toString(is);
55         System.out.println("result: " + result);
56 
57         
58         
59         // HttpURLConnection 傳送SOAP請求
60         System.out.println("HttpURLConnection 傳送SOAP請求");
61         URL url = new URL(wsdl);
62         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
63 
64         conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
65         conn.setRequestMethod("POST");
66         conn.setUseCaches(false);
67         conn.setDoInput(true);
68         conn.setDoOutput(true);
69         conn.setConnectTimeout(timeout);
70         conn.setReadTimeout(timeout);
71         
72         DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
73         dos.write(sb.toString().getBytes("utf-8"));
74         dos.flush();
75         
76         
77         BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
78         String line = null;
79         StringBuffer strBuf = new StringBuffer();
80         while ((line = reader.readLine()) != null) {
81             strBuf.append(line);
82         }
83         dos.close();
84         reader.close();
85         
86         System.out.println(strBuf.toString());
87     }
88 
89 }
複製程式碼

 響應報文如下:

複製程式碼
<?xml version="1.0" ?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <
S:Body>
      <
ns2:sayHelloResponse xmlns:ns2="http://demo.ls.com/">
        <
return>Hello World, ls</return>
      </
ns2:sayHelloResponse>
    </
S:Body>
  </
S:Envelope>
複製程式碼

------------------------------------------------------------------------------------  

SOAP的請求報文的格式是怎麼來的呢?

  答:(1)可用Eclipse測試WSDL檔案,則可得到想要的SOAP請求及響應報文,具體步驟如下圖:

第一步:

第二步:

 通過第一步,會在瀏覽器開啟如下的頁面

(2)saopui工具

  2、生成客戶端程式碼訪問

   a、通過 "wsimport"(JDK自帶)命令生成客戶端程式碼。進入命令列模式,執行 wsimport -s . http://localhost:9000/HelloWorld?wsdl,就會在當前目錄下生成客戶端程式碼。附圖:

 

  b、通過Eclipse生成客戶端程式碼