android下身分識別驗證方式調用webservice

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.