Volley simple learning using two--request

Source: Internet
Author: User

first, starting from the construction body of each post or GET request: Xxxrequest (a) stringrequestThe source code is as follows:
public class Stringrequest extends request<string> {private final listener<string> mlistener; /** * You can see that the final construction request is implemented by the requests class, and HTTP requests and responses are handled by request * * @param method The request {@link method} to Use;meth      OD is defined in Request * @param URL URL to fetch the string at * @param listener listener to receive the string response * @param errorlistener Error Listener, or NULL to ignore errors */public stringrequest (int method, String URL        , listener<string> Listener, Errorlistener Errorlistener) {Super (method, URL, errorlistener);    Mlistener = listener; /** default to GET request constructor */public stringrequest (String URL, listener<string> Listener, Errorlistener Errorlistener    {This (method.get, URL, Listener, errorlistener); }/** the two functions in the parent request are abstract *////callback data that the server responds to @Override protected void Deliverresponse (String response)    {Mlistener.onresponse (response); }//data sent to the server responseTo parse the function, you can see the main data in networkresponse///The Success function is clearly returned the first function is the parsed data @Override protected Response<string&gt ;        Parsenetworkresponse (networkresponse response) {String parsed;        try {parsed = new String (Response.data, Httpheaderparser.parsecharset (response.headers));        } catch (Unsupportedencodingexception e) {parsed = new String (response.data);    } return Response.success (parsed, httpheaderparser.parsecacheheaders (Response)); }}

(ii) can be inferred Jsonobject is also similar to the realization,
public class Jsonobjectrequest extends Jsonrequest<jsonobject>public abstract class Jsonrequest<t> extends Request<t>

1. Look Firstjsonobjectrequestdefinition of:
public class Jsonobjectrequest extends Jsonrequest<jsonobject> {/** can see Jsonobjectrequest the final construction request is also given to the request class for implementation * The entire code structure is similar to Stringrequest */public jsonobjectrequest (int method, String URL, jsonobject jsonrequest, Liste Ner<jsonobject> Listener, Errorlistener Errorlistener) {Super (method, url, (jsonrequest = = null)? null:js    Onrequest.tostring (), Listener, Errorlistener); } public jsonobjectrequest (String URL, jsonobject jsonrequest, listener<jsonobject> Listener, Errorlis Tener Errorlistener) {this (jsonrequest = = null?)    Method.GET:Method.POST, URL, jsonrequest, Listener, Errorlistener); }/*deliverresponse is implemented in the parent class Jsonrequest */@Override protected response<jsonobject> parsenetworkresponse (Ne Tworkresponse response) {try {string jsonstring = new String (Response.data, Httpheaderp            Arser.parsecharset (response.headers)); RetUrn response.success (new jsonobject (jsonstring), Httpheaderparser.parsecacheheaders (Response));        } catch (Unsupportedencodingexception e) {return response.error (new ParseError (e));        } catch (Jsonexception je) {return response.error (new ParseError (JE)); }    }}
2. View Jsonrequest
Public abstract class Jsonrequest<t> extends Request<t> {/** Request encoded format. */private static final Stri     ng Protocol_charset = "Utf-8"; /** The content contents of the request. */private static final String Protocol_content_type = String.Format ("Application/json;     charset=%s ", Protocol_charset);    Private final listener<t> Mlistener;     Private final String Mrequestbody; /** * Deprecated constructor for a jsonrequest which defaults to GET unless {@link #getPostBody ()} * or {@link #ge     Tpostparams ()} is overridden (which defaults to POST). */Public Jsonrequest (int method, string url, String requestbody, listener<t> Listener, Errorlistener Errorlistener) {Super (method, URL, errorlistener);//These are similar to stringrequest, nothing more than mrequestbody Mlistener = List        Ener;    Mrequestbody = Requestbody;    } @Override protected void Deliverresponse (T response) {mlistener.onresponse (response); } @Override Abstract Protected response<t> parsenetworkresponse (Networkresponse Response); /** here overrides the corresponding function in request to construct the specific contents of the request */@Override public String Getbodycontenttype () {return Protocol_c    Ontent_type; } @Override Public byte[] GetBody () {try {return mrequestbody = = null? null:mRequestBody.get        Bytes (Protocol_charset); } catch (Unsupportedencodingexception uee) {volleylog.wtf ("unsupported Encoding while trying to get the bytes            Of%s using%s ", Mrequestbody, Protocol_charset);        return null; }    }}

(c) The general practice of constructing xxxrequest can be summed up above,

1, constructs the real request to the parent class requset<xxx> to achieve-- Super (method, URL, errorlistener);

2. Define your own listener to Deliverresponse

3. Rewrite Parsenetworkresponse function to parse the data returned by the server response

(d) According to the above analysis, to define their own xxxrequest, such as XMLRequest to get the XML type of return data, here copy

(http://blog.csdn.net/guolin_blog/article/details/17612763) the code in

public class XMLRequest extends Request<xmlpullparser> {/********* here to replace the data type needed to parse ***********/private fin     Al listener<xmlpullparser> Mlistener; /********* here is basically exactly the same as the process described above ************************/public xmlrequest (int method, String URL, listener<        Xmlpullparser> Listener, Errorlistener Errorlistener) {Super (method, URL, errorlistener);    Mlistener = listener;        } public xmlrequest (String URL, listener<xmlpullparser> Listener, Errorlistener errorlistener) {    This (method.get, URL, Listener, errorlistener);        } @Override protected response<xmlpullparser> parsenetworkresponse (Networkresponse Response) { Try {/*************** implements the new Xmlrequset core, which resolves the data returned by the data to obtain the final parsing result *********************/String XM            lstring = new String (Response.data, Httpheaderparser.parsecharset (response.headers)); Xmlpullparserfactory factory = Xmlpullparserfactory.newinstaNCE ();            Xmlpullparser Xmlpullparser = Factory.newpullparser ();            Xmlpullparser.setinput (new StringReader (xmlstring));        Return response.success (Xmlpullparser, Httpheaderparser.parsecacheheaders (Response));        } catch (Unsupportedencodingexception e) {return response.error (new ParseError (e));        } catch (Xmlpullparserexception e) {return response.error (new ParseError (e));    }} @Override protected void Deliverresponse (Xmlpullparser response) {mlistener.onresponse (response); } }
It is also used in much the same way as stringrequest, where listener can be added to the server responseparsing code for the data:
 private requestqueue mrequestqueue;    Mrequestqueue = Volley.newrequestqueue (this);     String url = "Http://flash.weather.com.cn/wmaps/xml/china.xml"; response.listener<xmlpullparser> Listener = new response.listener<xmlpullparser> () {@Override P ublic void Onresponse (Xmlpullparser response) {//This should be accompanied by an analysis of response specific data log.d (TAG, Response.tost        Ring ());     }    }; Response.errorlistener Errorlistener = new Response.errorlistener () {@Override public void Onerrorresponse (        Volleyerror error) {LOG.E (TAG, Error.getmessage ());     }    };    XMLRequest xmlrequest = new XMLRequest (URL, Listener, errorlistener); Mrequestqueue.add (xmlrequest); 

(v) Look back at the original code of the request

1, first look at its constructor, is also the constructor of the previous several xxxrequest calls:

Public Request (int method, String URL, Response.errorlistener listener) {    Mmethod = method;                        The member variable is assigned a value of    murl = URL;    Merrorlistener = listener;    Setretrypolicy (New Defaultretrypolicy ());//Set retry policy     mdefaulttrafficstatstag = textutils.isempty (URL)? 0: Uri.parse (URL). GetHost (). Hashcode ();}
attach I, retry policy
public class Defaultretrypolicy implements Retrypolicy {        ....    /** The default socket timeout in milliseconds */public    static final int default_timeout_ms = 2500;//defaults socket time-out 
   
    /** the default number of retries */public    static final int default_max_retries = 1;  Default retry count    /** default Backoff multiplier */public    static final float Default_backoff_mult = 1f;//defaults compensation factor     P Ublic Defaultretrypolicy () {This        (Default_timeout_ms, default_max_retries, Default_backoff_mult);    }        ....}
   
andSetretrypolicythat is a simple setter function:
    /** The retry policy for this request. */    private retrypolicy mretrypolicy;     public void Setretrypolicy (Retrypolicy retrypolicy) {        mretrypolicy = retrypolicy;    }
2, the rest is a series of setter and getter function, the function used before is:
    Abstract protected response<t> parsenetworkresponse (Networkresponse Response);       Abstract protected void Deliverresponse (T response);
It can be seen that these two are abstract and require an override3, Jsonrequest also override some post body related functions, these functions to organize the parameters in the post request, the use can be self-overloading:
    private static final String default_params_encoding = "UTF-8";    Protected Map<string, string> Getparams () throws Authfailureerror {return null;    } protected String getparamsencoding () {return default_params_encoding; } public String Getbodycontenttype () {return ' application/x-www-form-urlencoded;    charset= "+ getparamsencoding ();     }/** * Returns the raw POST or PUT body to is sent. */Public byte[] GetBody () throws Authfailureerror {map<string, string> params = Getparams ();//From Above Getpar The definition of the AMS method shows that to use this method,//The Getparams method should be overloaded, or the GetBody () if (params) can be overloaded directly        ! = null && params.size () > 0) {return encodeparameters (params, getparamsencoding ());    } returnnull;     }/** * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string. */privatebyte[] Encodeparameters (map<sTring, string> params, String paramsencoding) {StringBuilder encodedparams = new StringBuilder (); try {for (map.entry<string, string> entry:params.entrySet ()) {Encodedparams.append (URL                Encoder.encode (Entry.getkey (), paramsencoding));                Encodedparams.append (' = ');                Encodedparams.append (Urlencoder.encode (Entry.getvalue (), paramsencoding));            Encodedparams.append (' & ');        } return Encodedparams.tostring (). GetBytes (paramsencoding); } catch (Unsupportedencodingexception uee) {thrownew runtimeexception ("Encoding not supported:" + paramsencod        ING, uee); }    }

Volley simple learning using two--request

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.