Android calls the WebService series of encapsulation capabilities

Source: Internet
Author: User

In a previous article, we simply described how Android makes WebService calls!

And often we in the project will be packaged before use! So how do we use the ability to encapsulate it?

I. Understanding commonality, mechanism, thinking extensible, independent, portability.

First of all, we have to communicate in Android, and that is handler,thread.

Due to the Android mechanism, we need to consider

    1. The UI thread cannot handle time-consuming operations, and obviously communication is a time-consuming operation. So we used the thread.

    2. The child thread cannot update the UI thread, so we need to use the handler mechanism to notify the UI thread to react

Due to the server language we need to consider

WebService Java and. NET are currently developed in 2 languages

Combined with the above considerations, then the general idea is not a bit of a clue!

Try to write it!

First create a class webservice

Basically the request has a start, is being requested, an error occurred, a success, the end of the request 5 states

We add handler to process the categorization of the message, of course, it can be directly defined here, and I am here to set an inner class as the screening class.

Class Msgcode {public final static int statr = 0x01;//start public final static int error = 0X02;//Error Public final static int sussce = 0x03;//successful public final static int finaly = 0x04;//End public final static I NT PROGRESS = 0x05;//in Request}

Next we think about what parameters we webservice request in general, we need the following 6 categories to list.

    1. Server URL

    2. Namespace URL

    3. The requested function name

    4. List of parameters requested

    5. Requested server category

    6. Handler Processing Message objects

The list is complete, then our thinking is more clear. At this point we create a start function, where the parameter list is requested with a map so that the form of key value is exactly the same as the WebService parameter form.

Public static void start (Final string sv_url, final string ns_url,             final String mthd,  final hashmap<string, object> params,             final boolean isdotnet, final handler callback)  {         new thread (new runnable ()  {              @Override              public void run ()  {               //webservice Call handling Method              }        }). Start ();     }

Now let's review the previous article in detail with the code

How Android makes WebService calls, we define a call to the specific function Start_ function, with the same parameters as start.

static void Start_ (String serviceurl, String Namespaceurl, String Servicemethod, Hashmap<string, object> Params, Boolean isdotnet, Handler Handler) {}

Now let's take a step-by-step look at how the previous article called

Build soapserializationenvelopesoapserializationenvelope evlp = new  Soapserializationenvelope (               &NBSP;&NBSP;SOAPENVELOPE.VER11);//corresponds to the ksoap 1.1 specification//Build soapobject soapobject soapobject =  new soapobject (Namespaceurl, servicemethod);//Build a Transfer parameter list//settings soapobject evlp.bodyout =  soapobject; //you can also be so evlp.setoutputsoapobject (soapobject);//setting is .netevlp.dotnet =  isdotnet;//There's a timeout time-out here. We can define a static constant 50s as a timeout within a class to modify private static int timeout = as needed  1000 * 50; Httptransportse hts = new httptransportse (serviceurl, timeout);//Call           Note, here is a actionurl is the result of Namespaceurl+servicemethod,//is generally a server?wsdl  Inside the targetnamespace+  function Namehts.call (ACTIONURL,&NBSP;EVLP);//Receive Results object result =  Evlp.getresponse ();//or object result =  evlp.bodyIn; 

Of course, the above code directly copy the past is not directly used, we think carefully, we lack of what!

First of all, we're missing a list of build parameters! Below I create a addparam function to add a parameter list by traversing HashMap

Private static void addparam (soapobject soapobject,             hashmap<string, object> params)  {         // TODO Auto-generated method stub         if  (Params != null && !params.isempty ())  {             Iterator iter =  Params.entryset (). iterator ();             while   (Iter.hasnext ())  {                 Map.Entry entry =  (Map.entry)  iter.next ();                 object key = entry.getkey ();       &nBsp;         object val = entry.getvalue ();                 propertyinfo pi  = new propertyinfo ();                 pi.setname (Key.tostring ());                 pi.setvalue (val);                 pi.settype (Val.getclass ());                 soapobject.addproperty (PI);                 // Of course if you just pass the string directly above Propertyinfo pi = new propertyinfo ();                 //after the comment off directly with the following also line                  // soapobject.addproperty (Key.tostring (),  val.tostring ());             }        }     }
Build the transfer parameter list with the following statement AddParam (Soapobject, params);

Let's see what's missing.

We have less handler mechanism to deal with, let us add! The Start_ function becomes like this.

Specific functions called by/**     *       *       *  @param  serviceUrl     *  @param  namespaceUrl      *  @param  serviceMethod     *  @param  params      *  @param  isDotNet     *  @param   Handler     */    static void start_ (String  serviceurl, string namespaceurl,             String serviceMethod, HashMap<String, Object> params,             boolean isdotnet, handler handler)  {         // TODO Auto-generated method stub        &nbsP string actionurl = namespaceurl + servicemethod;         handler.obtainmessage (MSGCODE.STATR). Sendtotarget ();         soapobject soapobject = new soapobject (Namespaceurl, servicemethod);         addparam (Soapobject, params);         soapserializationenvelope evlp = new soapserializationenvelope (  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SOAPENVELOPE.VER11);         evlp.bodyOut = soapobject;         evlp.dotNet = isDotNet;         Evlp.setoutputsoapobject (soapobject);         httptransportse hts  = new httptranspoRtSE (serviceurl, timeout);        try {             hts.call (ACTIONURL,&NBSP;EVLP);             object result = evlp.getresponse ();             if  (Result.getclass (). IsAssignableFrom ( Soapfault.class))  {                 handler.obtainmessage (Msgcode.error, result). Sendtotarget ();             } else {                 handler.obtainmessage (Msgcode.sussce, result). Sendtotarget ();            }         } catch  (httpresponseexception e)  {             // TODO Auto-generated catch block             handler.obtainmessage (Msgcode.error, e.getmessage ()). SendToTarget ();             e.printstacktrace ();         } catch  (ioexception e)  {             // TODO Auto-generated catch block             handler.obtainmessage (Msgcode.error, e.getmessage ()). Sendtotarget ();             e.printstacktrace ();         } catch  (xmlpullparserexception e)  {             // todo auto-generated catch block             handler.obtainmessage (MsgCode.ERROR, e.getMessage () ). Sendtotarget ();             e.printstacktrace ();         }         Handler.obtainmessage (msgcode.finaly). Sendtotarget ();     }

So we have a complete request WebService class is built!

The content of this article will be finished!

Friends who use this time will find a problem. How do we deal with this if we want to pass the object?

All right, everyone, next. Please look forward to the next article "Android Call WebService Series Object Build Pass"

This article is from the "Arps branding" blog, please be sure to keep this source http://laoyin.blog.51cto.com/4885213/1668989

Android calls the WebService series of encapsulation capabilities

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.