android下身份验证方式调用webservice

在企业开发领域,webservice还是经常被用到的服务体系,因为他对安全事务支持都比较好。


有时候,我们就需要在android下调用后端的webservice服务,因为在内部网络环境下,所有需要basic身份验证。


一般情况下,我们会用soap包来访问,但是soap包虽然封装的比较好,但是一旦出错很难找到原因。下面我们介绍一种简单的方式,通过http client post来访问webservice;


首先,我们把soap请求拼装成xml字符串,如下:

        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>"
                + " <GetAPACShippingPackage xmlns=\"xx/\">"
                + " <GetAPACShippingPackageRequest>"
                + " <TrackCode>123</TrackCode>"
                + " <Version>123</Version>"
                + " <APIDevUserID>123</APIDevUserID>"
                + " <APIPassword>123</APIPassword>"
                + " <APISellerUserID>123</APISellerUserID>"
                + " <MessageID>123</MessageID>"
                + " </GetAPACShippingPackageRequest>"
                + " </GetAPACShippingPackage>" + "</soap12:Body>"
                + " </soap12:Envelope>";

创建postMethod:

PostMethod postMethod = new PostMethod(
                "http://xx?wsdl");

声明他是一个soap请求:

        StringRequestEntity requestEntity = new StringRequestEntity(soapRequestData,"application/soap+xml; charset=UTF-8; type=\"text/xml\"","UTF-8");
        postMethod.setRequestEntity(requestEntity);

加上basic身份认证:

HttpClient httpClient = new HttpClient();
        httpClient.getState().setCredentials(new AuthScope("host", 80, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials("username", "password"));
        httpClient.getParams().setAuthenticationPreemptive(true);

最后,像正常的http请求一下,调用起来:

 int statusCode = httpClient.executeMethod(postMethod);
        if(statusCode == 200) {
            System.out.println("调用成功!");
            String soapResponseData = postMethod.getResponseBodyAsString();
            System.out.println(soapResponseData);
        }
        else {
            System.out.println("调用失败!错误码:" + statusCode);
        }

这里的返回值就是webservice返回的xml,需要我们解析这个xml文件来得到数据。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。