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文件来得到数据。

上一篇:maven仓库有jar包,还是找不到类


下一篇:[原创] Python3.6+request+beautiful 半次元Top100 爬虫实战,将小姐姐的cos美图获得