Android based on open Source network framework asychhttpclient, two-time package for common network request components

Source: Internet
Author: User

Web requests are an essential feature of all apps, and it's not very reasonable to assume that every development has rewritten a network request or copied the code from the past to a new app, and for this purpose I want to separate the entire Network request framework from the business logic, This avoids having to write the network request again every time, and then two times, based on my familiar asynchttpclient, encapsulates a network request framework.

Idea: The only function of the network request layer is to send the request, receive the response data, request cancellation, cookie processing these several functions, two times to help package these functions can directly call the package of good method.

Two help package codes such as the following:

1. Function Interface:

/********************************************************** * @ FileName: Disposedatalistener.java * @ file Rzq * @ Created: August 19, 2015 11:01:13 * @ File Description: * @ change history: August 19, 2015 Create the initial version number **************************************************** /public interface disposedatalistener{    /**     * Request Start callback Event processing     *    /public void OnStart ();    /**     * Request successful callback event handling     *    /public void onsuccess (Object responseobj);    /**     * Request failed callback event handling     *    /public void OnFailure (Object reasonobj);    /**     * Request re-connect callback event handling *    /public void onretry (int retryno);    /**     * Request Progress Callback Event Processing     *    /public void onprogress (long byteswritten, long totalsize);    /**     * Request End Callback Event Processing     *    /public void onfinish ();    /**     * Request Cancellation callback event handling     *    /public void OnCancel ();}


2. Request function Interface Adapter mode

public class Disposedatahandle implements disposedatalistener{    @Override public    void OnStart ()    {    }    @Override public void    onsuccess (Object responseobj)    {    }    @Override the public    void OnFailure ( Object reasonobj)    {    }    @Override public    void onretry (int retryno)    {    }    @Override Public    void OnProgress (Long byteswritten, long totalsize)    {    }    @Override public    void OnFinish ()    {    }    @Override public    void OnCancel ()    {    }}

3. Request Callback Event handling:

/********************************************************** * @ FileName: Basejsonresponsehandler.java * @ file Rzq * @ Created: August 19, 2015 10:41:46 * @ File Description: Server response base class, contains Java layer exception and business logic Layer exception Code Definition * @ change history: August 19, 2015 Create the initial version number **************** /public class Basejsonresponsehandler extends jsonhttpresponsehandler{/*    * The logic layer exception, may alter in different app */protected final String Result_code = "Ecode";    protected final int result_code_value = 0;    Protected final String error_msg = "emsg";    Protected final String empty_msg = ""; /** * The Java Layer exception */protected final int network_error =-1; The network relative error protected final int json_error =-2; The JSON relative error protected final int other_error =-3;    The Unknow error/** * interface and the handle class */protected class<?> mclass;    protected Disposedatahandle Mdatahandle; Public BasejsonresponsehanDler (Disposedatahandle datahandle, class<?> clazz) {this.mdatahandle = Datahandle;    This.mclass = Clazz;    } public Basejsonresponsehandler (Disposedatahandle datahandle) {this.mdatahandle = Datahandle;    }/** * Only handle the success branch (Ecode = = 0) */public void onsuccess (Jsonobject response) {} /** * Handle the Java exception and logic exception Branch (Ecode! = 0) */public void onfailure (Throwable thr        owobj) {} @Override public void onsuccess (int statusCode, header[] headers, jsonobject response) {    Onsuccess (response);    } @Override public void onfailure (int statusCode, header[] headers, throwable throwable, Jsonobject errorresponse)    {onfailure (throwable); }}/********************************************************** * @ file Name: commonjsonresponsehandler.java * @ file rzq * @ Created: August 19, 2015 Morning 11:01:13 * @ File Description: Where the business logic layer really handles, including Java layer exceptions and Business layer exceptions  * @ Change calendarHistory: August 19, 2015 Create the initial version number  **********************************************************/public class Commonjsonresponsehandler extends basejsonresponsehandler{    public Commonjsonresponsehandler ( Disposedatahandle datahandle)     {        super (datahandle);     }    public Commonjsonresponsehandler (Disposedatahandle datahandle, class<?

> Clazz)     {        super (Datahandle, clazz);    }      @Override     public void OnStart ()     {         mdatahandle.onstart ();    }     @Override     public void OnProgress (Long Byteswritten, long totalsize)     {         Mdatahandle.onprogress (Byteswritten, totalsize);    }     @Override     public void onsuccess (jsonobject response)     {         Handleresponse (response);    }     @Override     public void OnFailure ( Throwable throwobj)     {        mdatahandle.onfailure (new Logicexception (Network_error, Throwobj.getmessage ()));    }     @Override      pubLIC void OnCancel ()     {        mdatahandle.oncancel ();    }     @Override     public void onretry (int retryno)     {         mdatahandle.onretry (retryno);    }     @Override     public void OnFinish ()     {         Mdatahandle.onfinish ();    }    /**     * Handle the server response      */    private void Handleresponse (jsonobject response)     {         if (response = = null)         {     & nbsp      mdatahandle.onfailure (New Logicexception (Network_error, empty_msg));             return;        }        try        {            if (Response.has (result_code))             {                 if (response.optint (result_code) = = Result_code_value)                 {                     if (MClass = = null)                      {                         mdatahandle.onsuccess (response);                     }                     else                    {                        object obj = Responseentitytomodule.parsejsonobjecttomodule (response, MClass);                         if (obj! = null)        & nbsp;                {                             Mdatahandle.onsuccess (obj);                         }                         else                        &NBsp {                             mdatahandle.onfailure (New Logicexception (Json_error, empty_msg));                         }                     }                 }                else                 {                     if (Response.has (error_msg))                      {                         mdatahandle.onfailuRe (new Logicexception (Response.optint (Result_code), response                                .optstring ( error_msg));                    }                     else                     {                         mdatahandle.onfailure (new Logicexception (Response.optint (Result_code), empty_msg));                     }                }             }         &nbsp  else            {                 if (Response.has (error_msg))                 {                    mdatahandle.onfailure (New Logicexception (Other_error, response.optstring (error_msg)));                 }            }         }        catch (Exception e)          {            mdatahandle.onfailure (new Logicexception (Other_error, E.getmessage ()));             E.printstacktrace ();        }    }

4. Define the exception class yourself and encapsulate uniform processing for Java exceptions and business logic exceptions

/********************************************************** * @ FileName: Logicexception.java * @ file Rzq * @ created: August 19, 2015 10:05:08 * @ File Description: Define the Exception class yourself, return ecode,emsg to Business layer * @ change history: August 19, 2015 create an initial version number ******************************************* /public class Logicexception extends exception{private static final long Serialversionuid = 1l;/** * the SE  RVer return Code */private int ecode;/** * The server return error message */private String emsg;public logicexception (int Ecode, String emsg) {this.ecode = Ecode;this.emsg = emsg;} public int Getecode () {return ecode;} Public String getemsg () {return emsg;}}
5. Request to send the Ingress class Commonclient:
/********************************************************** * @ FileName: Commonclient.java * @ file Rzq * @ created: August 19, 2015 AM 11 : 38:57 * @ File Description: Universal HttpClient, support for re-connection, cancellation request, cookie Storage * @ change history: August 19, 2015 Create the initial version number **************************************** /public class Commonclient{private static asynchttpclient client;static{/** * Init the retry exception */asynchttpclient.allowretryexceptionclass (Ioexception.class); Asynchttpclient.allowretryexceptionclass (Sockettimeoutexception.class); Asynchttpclient.allowretryexceptionclass (connecttimeoutexception.class);/** * init The BLOCK retry exception * * Asynchttpclient.blockretryexceptionclass (Unknownhostexception.class); Asynchttpclient.blockretryexceptionclass (connectionpooltimeoutexception.class); client = new AsyncHttpClient ();} public static RequestHandle get (String URL, Asynchttpresponsehandler responsehandler) {return client.get (URL, ResponseHandler);} public static RequestHandle get (String URL, requestparams params, Asynchttpresponsehandler respoNsehandler) {return client.get (URL, params, responsehandler);} public static RequestHandle Get (context context, String URL, Asynchttpresponsehandler responsehandler) {return Client.get (context, URL, responsehandler);} public static RequestHandle Get (context context, String URL, requestparams params,asynchttpresponsehandler ResponseHandler) {return client.get (context, URL, params, responsehandler);} public static RequestHandle Get (context context, String URL, header[] headers, requestparams params, Asynchttpresponsehandler ResponseHandler) {return client.get (context, URL, headers, params, responsehandler);} public static RequestHandle post (String URL, Asynchttpresponsehandler responsehandler) {return client.post (URL, ResponseHandler);} public static RequestHandle post (String URL, requestparams params, Asynchttpresponsehandler responsehandler) {return Client.post (URL, params, responsehandler);} public static RequestHandle post (context context, String URL, requestparams params,asynchttpresponsehandler ResponseHandler) {return client.post (context, URL, params, responsehandler);} public static RequestHandle post (context context, string URL, httpentity entity, String contentType, Asynchttpresponsehandler ResponseHandler) {return client.post (context, URL, entity, ContentType, ResponseHandler);} public static RequestHandle post (context context, String URL, header[] headers, requestparams params,string contentType, A Synchttpresponsehandler ResponseHandler) {return client.post (context, URL, headers, params, ContentType, ResponseHandler);} public static RequestHandle post (context context, String URL, header[] headers, httpentity entity,string contentType, Asyn Chttpresponsehandler ResponseHandler) {return client.post (context, URL, headers, entity, ContentType, ResponseHandler) ;} /** * Calcel the context relative request * @param context * @param mayinterruptifrunning */public void calcelrequests (Con Text context, Boolean mayinterruptifrunning) {client.cancelrequests (context, mayinterruptifrunning);} /** Cancel current all request in App * @param mayinterruptifrunning */public void Cacelallrequests (Boolean mayinterruptif Running) {client.cancelallrequests (mayinterruptifrunning);} public static void Sethttpcontextattribute (String id, Object obj) {client.gethttpcontext (). SetAttribute (ID, obj);} public static Object Gethttpcontextattribute (String ID) {return client.gethttpcontext (). getattribute (ID);} public static void Removehttpcontextattribute (String id) {client.gethttpcontext (). removeattribute (ID);} /** * Set the cookie store * @param cookiestore */public static void Setcookiestore (Cookiestore cookiestore) {Client.setcoo Kiestore (Cookiestore);} /** * Remove the cookie store */public static void Removecookiestore () {Removehttpcontextattribute (clientcontext.cookie_ STORE);}}

6. Login Demo Use

The preservation of cookies,

public class Myapplicaton extends application {private static Myapplicaton app; @Overridepublic void OnCreate () {Super.onc Reate (); app = this;/** * Adds cookiestore to global commonclient, all cookies are available from Persistentcookiestore */ Commonclient.setcookiestore (New Persistentcookiestore (This));} public static Myapplicaton getinstance () {return app;}}

Response Body Processing:

   private void Requestlogin () {requestparams params = new Requestparams ();p arams.put ("MB", "");p arams.put ("pwd", ""); Commonclient.post (this, URL, params, new Commonjsonresponsehandler (new Disposedatahandle () {@Overridepublic void Onsuccess (Object responseobj) {log.e ("------------->", responseobj.tostring ());} @Overridepublic void OnFailure (Object reasonobj) {log.e ("----->", ((logicexception) reasonobj). Getemsg ());} @Overridepublic void OnProgress (Long byteswritten, long totalsize) {log.e ("------------->", Byteswritten + "/" + totalsize);}));

After the above package. HTTP-based features are available, assuming that some special features are encountered in development, and may be extended in accordance with detailed requirements.


Source code Download

Android based on open Source network framework asychhttpclient, two-time package for common network request components

Related Article

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.