標籤:webservice 調試 httpurlconnection類
前面提過webservice調試工具,如果有興趣動手寫測試代碼,那挺好的啊!
我也是這樣想的,有想法不妨去嘗試哦。那麼,我的程式中主要用到HttpURLConnection類,先拼接符合soap協議的xml字串資訊,再與webservice服務端建立串連後,發送http請求,接收完返回資訊後列印出來。流程上和SoapUI 調試工具的差不多的,下面提供測試程式的代碼,大家可以參考一下。
import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;public class Http {public String httpGet(String httpURL){String reqMsg = "<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">" +"<soapenv:Header>" +"<ns1:Username xmlns:ns1=\"http://service.webservice.ultrapower.com.cn\" soapenv:mustUnderstand=\"false\">username</ns1:Username>" +"<ns1:Password xmlns:ns1=\"http://service.webservice.ultrapower.com.cn\" soapenv:mustUnderstand=\"false\">userpw</ns1:Password>" +"</soapenv:Header>" +"<soapenv:Body>" +"<ns1:SendXML xmlns:ns1=\"http://service.webservice.ultrapower.com.cn\">" +"<ns1:requestXml>" +"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +"<ReadWhiteList>" +"<srcDeviceType>32</srcDeviceType>" +"<srcDeviceID>321101</srcDeviceID>" +"<Cmd>0</Cmd>" +"</ReadWhiteList>" +"</ns1:requestXml>" +"<ns1:busiKey>11</ns1:busiKey>" +"</ns1:SendXML>" +"</soapenv:Body>" +"</soapenv:Envelope>";URL url = null; HttpURLConnection httpURLConn= null; StringBuffer dataString = new StringBuffer(""); String temp = new String();try{ System.out.println(httpURL); url = new URL(httpURL); httpURLConn= (HttpURLConnection)url.openConnection(); httpURLConn.setDoOutput(true); httpURLConn.setRequestMethod("POST"); httpURLConn.setConnectTimeout(300*1000);//300s逾時 httpURLConn.setRequestProperty("User-Agent","Apache-HttpClient/4.1.1 (java 1.5)"); httpURLConn.setRequestProperty("Content-Type","application/soap+xml;charset=UTF-8;action=\"urn:SendXML\""); OutputStream out = httpURLConn.getOutputStream(); out.write(reqMsg.toString().getBytes()); httpURLConn.connect(); InputStream in =httpURLConn.getInputStream(); BufferedReader bd = new BufferedReader(new InputStreamReader(in)); while((temp=bd.readLine())!=null) { dataString.append(new String(temp.getBytes())); } in.close(); bd.close(); } catch (Exception e){ e.printStackTrace(); } finally{ if(httpURLConn!=null){ httpURLConn.disconnect(); } } try{ System.out.println(new String(dataString.toString().getBytes("gbk"),"utf-8")); }catch(Exception e){ e.printStackTrace(); } return dataString.toString();}public static void main(String[] arg){Http pm = new Http();pm.httpGet("http://132.xx.xxx.xx:8080/xxx//xxx?wsdl");}}
有沒有覺得拼接的這個xml,有點偏複雜?這個webservice服務端弄了soaphead 安全機制,沒辦法,用戶端要求這樣弄。往後再介紹一下這個帶soaphead 安全機制的webservice服務端吧。
轉載請說明出自whilejolly:http://blog.csdn.net/seedingly/article/details/39054609
【webservice】調試方法篇(二)