Android uses ksoap2-android to call WebService

Source: Internet
Author: User

Today's mobile devices are simply not able to open the network connection, the exchange of data. Recent learning is how to call the remote webservice on the Android side, all say WebService is a SOAP protocol based remote call standard, for this protocol understanding is not deep, know WebService can be different operating system platform, different languages, Different technologies are integrated into one piece, the Android SDK does not directly call the WebService library, the most common is the use of ksoap2-android this third-party SDK, click to open the link, and then the same as other third-party jar package into the Android project.

1, define WebService's namespace and URL

<name= "NameSpace">http://tempuri.org/</string  ><name= "serviceurl_203">/http Public.ebanji.cn/web5/server/ischoolserver.asmx</string>

2, create Httptransportse Transfer object: Httptransportse HT = new Httptransportse (Service_url); Service_url is the URL for WebService service

New Httptransportse (serviceurl); Ht.debug=true;

3, Instantiate Soapobject object: Soapobject soapobject = new Soapobject (Service_namespace, methodName); The first parameter represents the namespace of webservice, and the WebService namespace can be found from the WSDL document. The second parameter represents the name of the WebService method to invoke.

New Soapobject (NameSpace, methodName);

4, create envelop object using SOAP1.1 protocol: soapserializationenvelope envelope = new Soapserializationenvelope (SOAPENVELOPE.VER11); Sets the version number of the SOAP protocol, based on the version number of the service-side webservice.

New Soapserializationenvelope (SOAPENVELOPE.VER11);


5, set the parameter value of the calling method, if there is no parameter, can be omitted: for example Soapobject.addproperty ("name", value);

if (param_list!=null) {    for (int i=0;i<param_list.length ();i++)    {        Request.addproperty (Param_list.getjsonobject (i). getString ("name"), Param_list.getjsonobject (i). GetString ("value"));}    }

6, set with. NET provides webservice to maintain good compatibility

Envelope.dotnet=true;

7, remember to set bodyout property Envelope.bodyout = Soapobject;

envelope.bodyout=Request;envelope.setoutputsoapobject (request);

8, call Webservice:ht.call (service_namespace+methodname, envelope);

Ht.call (namespace+methodname, envelope);

9, parse the SOAP message for the server response

Soapobject result == result.getproperty (0). toString ();

The source code for the built-in collation is attached:

/*** Call Server method *@paramNameSpace to call the WebServices namespace *@paramserviceurl to invoke WebServices's absolute address *@paramMethodName which method name to call WebServices *@paramparam_list The array of arguments to enter, no write null *@returnback to server data *@throwsjsonexception Parameter Error*/PrivateString get_webservice_1_string (String namespace,string serviceurl,string methodname,jsonarray param_list)throwsjsonexception{Try{Soapobject Request=NewSoapobject (NameSpace, methodName); if(param_list!=NULL){             for(intI=0;i<param_list.length (); i++) {Request.addproperty (Param_list.getjsonobject (i). GetString ("Name"), Param_list.getjsonobject (i). GetString ("value"))); }} log.d ("Informacation", "parameter correct"); Soapserializationenvelope Envelope=NewSoapserializationenvelope (SOAPENVELOPE.VER11); Envelope.bodyout=request; Envelope.dotnet=true;         Envelope.setoutputsoapobject (Request); Httptransportse HT=NewHttptransportse (serviceurl); Ht.debug=true; LOG.D ("Informacation", "Network is turned on, access address is:" +serviceurl); Ht.call (NameSpace+methodName, envelope); Soapobject result=(Soapobject) Envelope.bodyin; returnResult.getproperty (0). toString (); }     Catch(xmlpullparserexception e) {//TODO Auto-generated catch blockLOG.D ("Informacation", "Xmlpullparserexception Error:" +e.tostring ()); }Catch(IOException e) {log.d ("Informacation", "IO Error:" +e.tostring ()); }    Catch(Exception e) {log.d ("Informacation", "it is possible that the method inside the parameter is wrong, or there is no such method, the wrong reason:" +e.tostring ()); }    return"";}

This is the main implementation of the remote call WebService code, the other implementation in the activity can be done, but there is also a problem, that is, Android multithreading problem, when calling WebService, in order to prevent the appearance of ANR, cannot be done in the main thread and requires another thread to execute, because the child threads involve UI updates, and the Android main thread is threads that are unsafe

Another thread is called WebService

/*** The service called is Webservice_1 *@paramcontext to pass in activity *@parammessage used to return messages *@paramMethodName Method name passed in *@paramParam_list to pass in the parameters and values of the method, such as [{' Name ': ' Method name ', ' Value ': ' Method value '},{' name ': ' 2 ', ' Value ': ' 2 '}]*/ Public voidget_webservice_1_connect (Message message,string methodname,jsonarray param_list) { This. Target_message=message;  This. Namespace=context_this.getstring (r.string.namespace);  This. Methodname=MethodName;  This. param_list=param_list; if(!isnetworkconnected ()) {Toast.maketext (Context_this,"Network is not turned on, please open the network", Toast.length_long). Show (); return ; } Thread Thread=NewThread (runable); Thread.Start ();}

The following is an anonymous thread class

/*** thread, send the data returned by the server*/Runnable runable=NewRunnable () {@Override Public voidrun () {Try{String value= Get_webservice_1_string (soapconnect. This. Namespace,soapconnect. This. Serviceurl,soapconnect. This. MethodName
, Soapconnect. This. Param_list); Bundle Bundle=Target_message.getdata (); Bundle.putstring ("Data", value); Target_message.setdata (bundle); Target_message.sendtotarget (); } Catch(Exception e) {log.d ("Informacation", "Thread Error"); } }};

The next step is to write the method written above to call WebService and write the handle override Handlemessage method to implement the processing of the data after the call is completed

Methods for writing calls to WebService

/*** Remote Call * *@paramLocal_methodname The local method to return *@paramRemote_methodname to invoke the remote method *@paramparam_list to invoke the parameters of the remote method*/Private voidRemote_calls (MethodName Local_methodname,intRemote_methodname, Jsonarray param_list) {    //Calling Server MethodsSoapconnect sc =NewSoapconnect (documentboxcenterlistactivity. This); MyHandler Handler=NewMyHandler (); Message Message=Handler.obtainmessage (); Bundle Bundle=NewBundle (); Bundle.putstring ("MethodName", local_methodname.tostring ()); Message.setdata (bundle);SC. Get_webservice_1_connect (Message, documentboxcenterlistactivity. This. GetString (Remote_methodname), param_list);}

Write handle override Handlemessage method to process the data after the call is complete

 /**   * Custom Handler The data sent back specifically to this activity processing server  */ class  myhandler extends   Handler {@Override public  void   Handlemessage (Message msg) { log.e (" Informacation "," data returned correctly ");  if  (Msg.getdata (). Get ("MethodName") == "Data" 
     
      ));    
      super  .handlemessage (msg); }};

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.