手把手教你SOAP访问webservice并DOM解析返回的XML数据(转)

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层节点的属性值。 

posted @ 2017-07-05 17:56  herizai  阅读(11800)  评论(0编辑  收藏  举报