Android calls Web Service

Source: Internet
Author: User

Make a web service with whatever you want. Assume that the obtained web service address is as follows:

Http: // 192.168.0.100/Android/webservice1.asmx

In this web service, a sum function is provided, and its implementation is as follows:

Publicint sum (int A, int B ){

Return A + B;

}

In Android, you can call

Publicvoid callws () throws parserconfigurationexception {

Final string server_url = "http: // 192.168.0.100/Android/webservice1.asmx/sum ";

Httppost request = new httppost (server_url );

List Params = new arraylist ();

Params. Add (New basicnamevaluepair ("A", "1 "));

Params. Add (New basicnamevaluepair ("B", "2 "));

Try {

Request. setentity (New urlencodedformentity (Params, HTTP. utf_8 ));

Httpresponse = new defaulthttpclient(.exe cute (request );

String result = "";

If (httpresponse. getstatusline (). getstatuscode ()! = 404 ){

Result = entityutils. tostring (httpresponse. getentity ());

}

New alertdialog. Builder (this). settitle ("hint"). setmessage (result)

. Setpositivebutton ("OK", null). Show ();

} Catch (exception e ){

New alertdialog. Builder (this). settitle ("hint"). setmessage (

E. getmessage (). setpositivebutton ("OK", null). Show ();

}

}

The above method can correctly obtain the Web service return value, but it is a complete XML and needs to be further parsed to get the desired result.

The resolution method is as follows:

Documentbuilderfactory factory = documentbuilderfactory. newinstance ();

Documentbuilder builder = factory. newdocumentbuilder ();

Inputstream is = new bytearrayinputstream (result. getbytes ("UTF-8 "));

Document dom = builder. parse (is );

String res = Dom. getdocumentelement (). getchildnodes (). Item (0). getnodevalue ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.