標籤:webservice android 企業
在企業開發領域,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檔案來得到資料。
android下身分識別驗證方式調用webservice