手把手教你SOAP訪問webservice並DOM解析返回的XML資料

來源:互聯網
上載者:User

標籤:class   返回   use   ace   ica   例子   asmx   etc   修改   

http://blog.csdn.net/u012534831/article/details/51357111

前言: 
目前我們項目組還在採用webservice這種http方式,並且某些網站服務提供的對外介面還在採用webservice方式,因此就總結了一下寫了這篇文章。

以soap1.2的請求為例,在例子裡我們傳進去使用者名稱和密碼給服務,服務返回一個xml資料。 
首先我們來開一下soap1.2的request,

//wsdl,例:OrderApp.asmxPOST /******App.asmx HTTP/1.1//這兒填寫服務地址Host: 100.100.100.100Content-Type: application/soap+xml; charset=utf-8Content-Length: length<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  <soap12:Body>    <Login xmlns="我的項目">      <UserName>string</UserName>      <PassWord>string</PassWord>    </Login>  </soap12:Body></soap12:Envelope>

接下來,我們在代碼裡拼接請求體:

/** * arg1為第一個參數鍵,arg2為第一個參數值,arg3為第二個參數鍵,arg4為第二個參數值, *method為方法名,xmlns為命名空間 */    public void initSoap(String arg1,String arg2,String arg3,String arg4,String method,String xmlns) {        String soapRequestData = "<?xml version=\"1.0\"       encoding=\"utf-8\"?>"                + "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""                + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""                + " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"                + " <soap12:Body>"                + "<"+method+""+"xmlns="+"\""+xmlns+"\""//                + " <Login xmlns=\"我的項目\">"                + "<"+arg1+">"+arg2+"</"+arg1+">"                + "<"+arg3+">"+arg4+"</"+arg3+">"//                + " <UserName>"+"YQPIS0670"+"</UserName>"//                + " <PassWord>"+"YQPIS0670"+"</PassWord>"                + " </Login>"                 + "</soap12:Body>"                + " </soap12:Envelope>";    }

第二步,開啟線程並執行訪問

new Thread(new Runnable() {    @Override    public void run() {    // TODO Auto-generated method stub    PostMethod postMethod = new PostMethod(    "服務地址,即上面request中的host+連接埠號碼+post");    // 然後把Soap請求資料添加到PostMethod中    byte[] b = null;    try {    b = soapRequestData.getBytes("utf-8");        } catch (UnsupportedEncodingException e) {                // TODO Auto-generated catch block                e.printStackTrace();        }    InputStream is = new ByteArrayInputStream(b, 0, b.length);    RequestEntity re = new InputStreamRequestEntity(is,            b.length, "application/soap+xml; charset=utf-8");    postMethod.setRequestEntity(re);    // 最後產生一個HttpClient對象,並發出postMethod請求    HttpClient httpClient = new HttpClient();        try {        int statusCode = httpClient.executeMethod(postMethod);            if (statusCode == 200) {                Log.d("soapRequestData", "調用成功!");                StringBuffer buffer = new StringBuffer();                // 解析器 工廠類                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                DocumentBuilder db = dbf.newDocumentBuilder();                //返迴流式資料                InputStream soapResponseData = postMethod                            .getResponseBodyAsStream();                Document dm = db.parse(soapResponseData);                // element和node是同一概念                // 不同的是element提供更多方法            if (dm.getElementsByTagName("Root").item(0)                .getFirstChild() != null) {                // j是Root即根節點下面節點個數                for (int j = 0; j < dm  .getElementsByTagName("Root").item(0)                           .getChildNodes().getLength(); j++) {               String result3 = dm.getElementsByTagName("Root")                                 .item(0).getChildNodes().item(j).getTextContent();                buffer.append(result3);              }            }         } else {        Log.d("soapRequestData", "調用失敗!錯誤碼:" + statusCode);        }    } catch (HttpException e) {    // TODO Auto-generated catch block            e.printStackTrace();    } catch (IOException e) {    // TODO Auto-generated catch block            e.printStackTrace();    } catch (ParserConfigurationException e) {    // TODO Auto-generated catch block            e.printStackTrace();    } catch (SAXException e) {            // TODO Auto-generated catch block            e.printStackTrace();    }  }}).start();

大家可以看下我的xml資料:

<Root><Result>1</Result><Message>登入成功</Message><MemberIDCard>YQPIS0670</MemberIDCard><UserName>祁宏濤</UserName><Birthday>2010-11-04</Birthday><Photo>...</Photo><Telephone/><MemberState>當前會員</MemberState><MemberStatus>友情會籍</MemberStatus><MemberSex>12ee640d-a037-497e-966e-91fc2186c8b4</MemberSex><Nationality>175f0624-29d1-4b88-9d97-d72ebb1e6a1c</Nationality><MemberSexMemo>男</MemberSexMemo><NationalityMemo>中國</NationalityMemo></Root>

如果有多層節點,可以自己修改dm.getElementsByTagName(“Root”) .item(0).getChildNodes().item(j).getTextContent() 
為dm.getElementsByTagName(“Root”) .item(0).getChildNodes().item(j).getChildNodes().item(k).getTextContent();即為3層節點的屬性值。 

手把手教你SOAP訪問webservice並DOM解析返回的XML資料(轉)

聯繫我們

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