1. 程式人生 > >手把手教你SOAP訪問webservice並DOM解析返回的XML數據(轉)

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

3層 cor lock pos dom解析 tco 前言 nbsp encoding

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

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

以soap1.2的請求為例,在例子裏我們傳進去用戶名和密碼給服務,服務返回一個xml數據。
首先我們來開一下soap1.2的request,

//wsdl,例:OrderApp.asmx
POST /******App.asmx HTTP/1.1
//這兒填寫服務地址
Host: 100.100.100.100
Content-Type: application/soap+xml; charset=utf-8
Content-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數據(轉)