The Android program uses SOAP to invoke the remote WebService service

Source: Internet
Author: User
Tags soap

In today's applications, it is impossible not to use the network, and the backend must be supported by the server. Today, the most common way to invoke HTTP is get, post, and return JSON or XML data. But there is also a common form of calling WebService. Now let's implement the use of the SOAP Simple Object Access protocol on the Android side to invoke the WebService data. The main requirement is to return this number to the operator, card type, and attribution information based on a mobile phone number.

(1) First download a ksoap jar package from the Internet, put in the Project Libs folder, I also provide Baidu network disk download: Http://pan.baidu.com/s/1o6svnC2.

(2) Recommend a site that can call WebService, which provides a lot of services, http://www.webxml.com.cn/zh_cn/index.aspx.

(3) In the activity of the implementation of the Code as follows: The main interface display operation, and initialization of some webservice call parameters, such as URL address, namespace, method name, parameter list, etc.

Package Com.example.testwebservice2;import Java.util.hashmap;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.textview;public class Webserviceactivity extends Activity {private Context context;private static final String URL = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";// The requested urlprivate static final string NAMESPACE = "http://WebXml.com.cn/";//The requested namespace; private static final String METHODNAME = "Getmobilecodeinfo"; Method name, obtain the domestic mobile number belongs to the province, the region and the mobile card type information; private EditText phonenum;private Button query;private TextView showresult;private Handler Handler = new Handler () {//refresh interface; public void Handlemessage (Message msg) {String myData = Msg.getdata (). GetString (" Data ");//This is fully parsed and used for display; if (myData! = NULL | |!" ". Equals (MyData)) {Showresult.settext (MyData);};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); this.context = This;initview (); Query.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//Mobile number (segment) String phonesec = Phonenum.gettext (). toString (). Trim ();//simply determine if the user entered the mobile number (segment) is legal if ("". Equals (phonesec) | | Phonesec.length () < 7) {//input not valid, Phonenum.seterror ("You have entered the mobile phone number (paragraph) is wrong! "); Give the error hint Phonenum.requestfocus ();//TextView Empty Phonenum.settext ("") that displays the query result; Responseonclick (); Enter no problem, start requesting data;}}); private void Initview () {phonenum = (EditText) Findviewbyid (r.id.phone_sec); query = (Button) Findviewbyid (r.id.query_ BTN); Showresult = (TextView) Findviewbyid (r.id.result_text);} private void Responseonclick () {httpthread thread = new Httpthread (handler, context); hashmap<string, object> params = new hashmap<string, object> (); String phonesec = Phonenum.gettext (). toString (). Trim ();//telephone number; Params.put ("Mobilecode", Phonesec);//Mobilecode: string, cell phone number, minimum first seven digits; Params.put ("UserId", "");//string, free user is an empty string; Thread.dostart (URL, NAMESPACE, METHODNAME, params);}}

(4) Create a new thread class, inherit from thread, mainly do network operation to access WebService. Receives the returned data and passes it to the activity.

Package Com.example.testwebservice2;import Java.util.hashmap;import Java.util.iterator;import java.util.Map;import Java.util.map.entry;import Org.ksoap2.soapenvelope;import Org.ksoap2.serialization.soapobject;import Org.ksoap2.serialization.soapprimitive;import Org.ksoap2.serialization.soapserializationenvelope;import Org.ksoap2.transport.httptransportse;import Android.app.progressdialog;import Android.content.Context;import Android.os.bundle;import android.os.handler;import android.os.message;import Android.util.log;class HttpThread Extends Thread {private Handler Handler = null;private Context context = null;private String url = null;private string nam Espace = null;private String methodName = null; hashmap<string, object> params = new hashmap<string, object> ();//parameter list; private ProgressDialog ProgressDialog = null;//Constructor public httpthread (Handler Handler, Context context) {This.handler = Handler;this.context = Co ntext;} /** * Start Thread *//** * The four parameters to be passed to the server are: (1) URL (2) namespace (3) methodName (4) parameter list * * @param URL * @param namespace * @param methodName * @param params */public void dostart (string url, string namespace, String methodname,hashmap<string, object> params) {This.url = Url;this.namespace = namespace; This.methodname = Methodname;this.params = Params;progressdialog = Progressdialog.show (Context, "Prompt", "Requesting please wait ...", true); This.start ();//start this thread;}/** * thread run */@Overridepublic void run () {try {//Web service Request Soapobject result = (soapobje CT) callwebservice (); LOG.I ("Httpthread_getpropertycount", Result.getpropertycount () + ""); LOG.I ("httpthread_getproperty (0)", result.getproperty (0) + "");//Construction Data String value = Null;if (Result! = NULL && RE Sult.getpropertycount () > 0) {for (int i = 0; i < Result.getpropertycount (); i++) {soapprimitive primitive = (soappr imitive) Result.getproperty (i); value = Primitive.tostring ();} /** * The value obtained here is WebService: 18710498511: Shaanxi Xi ' an Shaanxi Mobile Global Pass card *///log.i ("Httpthread_value", value);// Cancel Progress Box Progressdialog.dismiss ();//ConstructionMessage msg = Handler.obtainmessage (); Bundle bundle = new Bundle (), bundle.putstring ("Data", value);//pass to interface for display; Message.setdata (bundle); Handler.sendmessage (message),///pass to the activity Handmessage () to be processed,}//if} catch (Exception e) {e.printstacktrace ();}} Run ();p rivate Object callwebservice () {String soap_action = namespace + methodname;//namespace + method name; Soapobject request = NE W Soapobject (namespace, methodName);//Create a Soapobject instance//Generate a SOAP request message that calls the Web service method Soapserializationenvelope Envelope  = new Soapserializationenvelope (SOAPENVELOPE.VER11);//set. NET Web serviceenvelope.dotnet = true;//Request parameter if (params! = NULL &&!params.isempty ()) {for (Iterator it = Params.entryset (). Iterator (); It.hasnext ();) {map.entry<string, object> e = (Entry) it.next (); Request.addproperty (E.getkey (). toString (), E.getvalue ());}} Send request Envelope.setoutputsoapobject (requests); Httptransportse transport = new Httptransportse (URL); Soapobject result = null;try {//Web service Request Transport.call (Soap_action,envelope); result = (Soapobject) Envelope.bodyin;} catch (Exception ex) {ex.printstacktrace ();} LOG.I ("Result", result.tostring ()); return result;} Callwebservice ();} Httpthread class;

(5) Program operation result

.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The Android program uses SOAP to invoke the remote WebService service

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.