In the field of enterprise development, WebService is often used as a service system because he is better at supporting security affairs.
Sometimes we need to downgrade the backend WebService service on Android, because in an internal network environment, all basic authentication is required.
In general, we will use SOAP packets to access, but although the SOAP package is better encapsulated, but once the error is difficult to find the cause. Here we introduce a simple way to access WebService via HTTP client post;
First, we assemble the SOAP request into an XML string, as follows:
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</message Id> "+" </GetAPACShippingPackageRequest> "+" </GetAPACShippingPackage> "+" </soap12:Body> " + "</soap12:Envelope>";
Create Postmethod:
Postmethod Postmethod = new Postmethod ( "http://xx?wsdl");
Declares that he is a SOAP request:
Stringrequestentity requestentity = new Stringrequestentity (Soaprequestdata, "application/soap+xml; charset=UTF-8; Type=\ "Text/xml\" "," UTF-8 "); Postmethod.setrequestentity (requestentity);
Plus basic identity authentication:
HttpClient HttpClient = new HttpClient (); Httpclient.getstate (). SetCredentials (New Authscope ("host", and Authscope.any_realm), new Usernamepasswordcredentials ("username", "password")); Httpclient.getparams (). Setauthenticationpreemptive (True);
Finally, like a normal HTTP request, call up:
int statusCode = Httpclient.executemethod (Postmethod); if (StatusCode = =) { System.out.println ("Call succeeded! "); String soapresponsedata = postmethod.getresponsebodyasstring (); System.out.println (Soapresponsedata); } else { System.out.println ("The call failed! Error code: "+ StatusCode); }
The return value here is the XML returned by webservice, and we need to parse the XML file to get the data.
Android under authentication method call WebService