20行代碼完成WebService請求

在java應用程序中使用webservice時大部人應該都是通過JDK工具從wsdl描述文件生成java代碼拷貝到項目中去訪問調用,這種方式簡單快捷但是你永遠不知道他的調用過程是怎麼樣的。。。
其實JDK中已經自帶了請求SOAP協議的類與方法,通過工具生成的java類也是採用它來完成整個調用過程的,但是它的代碼不便於閱讀和理解。。。
廢話不說了,貼代碼...
我們採用驗證erp用戶名密碼的webservice作爲研究對象。。。。

1.   public static void main(String[] args) throws Exception {

2.   //構建請求對象

3.   SOAPMessage reqMsg =MessageFactory.newInstance().createMessage();

4.   SOAPEnvelope envelope =reqMsg.getSOAPPart().getEnvelope();

5.   SOAPBody body = envelope.getBody();

6.   SOAPBodyElement getMessage =body.addBodyElement(envelope.createName("Verify", null,"http://360buy.com/"));//ERP用戶名密碼驗證方法

7.   //構建參數

8.   Map<String, String> data = new HashMap<String,String>();

9.   data.put("name", "bjxxx");//你的ERP賬號

10. data.put("password","123456");//你的ERP密碼

11. //設置參數

12. for(Map.Entry<String, String> entry : data.entrySet()) {

13. SOAPElement param =getMessage.addChildElement(entry.getKey());

14. param.addTextNode(entry.getValue());

15. }

16. SOAPConnection con= SOAPConnectionFactory.newInstance().createConnection();

17. SOAPMessageresponse = con.call(reqMsg,"http://erp1.360buy.com/hrmservice/DeptWebService.asmx");

18. con.close();

19. Node node =response.getSOAPBody().getFirstChild();//VerifyResponse

20. boolean res = node.hasChildNodes();//認證失敗沒有返回任何節點信息,認證成功會返回用戶信息(可以深度解析獲取用戶詳細資料)

21. System.out.println("認證結果:"+res);

22. }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章