Home Car Wash app---android Client Development Network Framework encapsulation Introduction (i)

Source: Internet
Author: User
Tags response code set time
<span id="Label3"></p><p style="text-align:center"><p style="text-align:center"><strong><span style="font-size:18px">Home Car Wash app---android Client Development Network Framework encapsulation Introduction (i)</span></strong><br></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">the previous article gave you a brief introduction to some of the business, <span style="white-space:pre"></span> </span> <span style="font-size:14px"><strong><span style="color:#3333ff">Home Car Wash app---android Client Development preface and business Introduction</span></strong></span> <span style="font-size:14px">, this article introduces you to the network box</span> <span style="font-size:14px">rack, have also learned some of the open source network communication architecture, also probably see some source code, such as afinal, volley, andbase, android-async-http</span> and <span style="font-size:14px">so on, each have their own advantages and disadvantages, they have also encapsulated some simple network architecture, there are many places need to pay attention to and optimization, here is not posted out caught dead,</span> <span style="font-size:14px">interested friends can check out the open source projects mentioned above, as well as view the previously organized blogs:</span> <span style="color:rgb(51,51,255); font-size:14px"><strong>Android Open source framework (collation)</strong></span> <span style="font-size:14px">do the related study, here does not introduce too much. </span></p></p><span style="font-size:14px"><span style="font-size:14px"><br><span style="white-space:pre"></span>This project uses the communication framework is <span style="color:#000099">Android-async-http</span>, has also written an article to its brief introduction,<strong><span style="color:#3333ff">android-async-http Open Source project introduction and the use Method</span></strong> , everybody can simply understand under, In this project, a series of encapsulation is done based on the Schema's request access to the data and the return of the data results.<br></span></span><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px"><span style="white-space:pre"></span>Here to share my ideas and ideas, and everyone to study together. This can be understood for network requests, request<span style="color:#cc0000">---></span> include (requests <strong></strong> </span> , requests, requests, requests <span style="font-size:14px"> <strong>fail, request ends</strong> ),</span> <span style="font-size:14px"> and the server response to the success of the data, data analysis of the results, storage and other processing, The basic framework is so, the personal feel</span> that <span style="font-size:14px">there is not perfect, the total feel that the return of the request data can be processed again, <span style="font-size:14px">further optimization, then how</span> ? </span></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">I think that, after making the request, the data obtained is expected to be resolved by the completed data, rather than from the return of the results of the resolution, that is, <span style="color:#cc0000">after the request has been completed</span> <span style="white-space:pre"></span> </span> the <span style="font-size:14px"><span style="color:#cc0000">result of the data is parsed, and the returned result is already directly</span></span> <span style="font-size:14px"> <span style="color:#cc0000">the object to Use. </span>in this case, the entire request parsing is much more convenient. </span></p></p><p><p><br></p></p><p><p><span style="font-size:14px">So what exactly is the effect? Let's look at a login request example Below:</span></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">private void Login (String name,string pwd) {genericdatamanager mdatamanager = genericdatamanager.getinstance ();// General network Management class Requestparams Mparams = requestparameterfactory.getinstance (). login (name, pwd);// Request parameter Management class Mdatamanager.datarequest (0,constants.request.get, requesturl.url_login, mparams,new ResultParser (), this); /execute Network request}</pre></pre><br><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">It takes only <span style="color:#ff0000">3 lines of code</span> to initiate a request, so how do you use it in your Activity? We threw out a <span style="color:#ff0000">irequestcallback</span> request Response Callback interface, which provides three callback methods for the Activity implementation:</span></p></p><p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">/** * Irequestcallback of Washer * Request Response Callback interface * @author Gao_chun */public interface irequestcallback {public void Onreq Ueststart (int requestid);//start request public void onrequestsuccess (int requestid,int statuscode,result<?> Result );//request succeeded, return request id, Status response code, data result (parsed data Object) public void Onrequesterror (int requestid,throwable error);//request error}</pre></pre><p><p></p></p><p><p><br></p></p><span style="font-size:14px"><span style="font-size:14px"> <strong><span style="color:#ff0000">note:</span></strong>RequestID is the request id, in order to distinguish which request, for example: an Activity needs to have two or more times of the request, how to distinguish the specific request in the callback? Use RequestID to Differentiate.<br><br></span></span><p><p><span style="font-size:14px">You only need to implement the interface in the Activity and implement the specific method to get the Data:</span></p></p><p><p></p></p><pre name="code" class="java">/******************************************************************************* * * Copyright (c) Weaver Info Tech Co. LTD * * loginactivity * * App.ui.activity.LoginActivity.java * todo:file description or class Description. * * @author: Gao_chun * @since: 2015-6-23 * @version: 1.0.0 * * @changeLogs: * 1.0.0:first created this class. * ******************************************************************************/package org.gaochun.activity;/* * * @author Gao_chun * */public class Loginactivity extends titleactivity implements Irequestcallback{public Context Conte xt; @Overrideprotected void onCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); context = this; Initui ();} private void Initui () {setcontentview (r.layout.activity_login); settitle (r.string.text_login);} @Overridepublic void Onrequeststart (int requestid) {//onrequeststart//can be displayed here dialog} @Overridepublic void onrequestsuccess (int requestid, int statusCode, result<?> Result) {//onrequestsuccesslog.i (TAG,result.getmessage () + "--" +result.getstatus () + "--" +result.getdata ());//data printing} @Overridepublic void Onrequesterror ( int requestid, throwable error) {//onrequesterrorlog.e (tag,error.getmessage ());//request failed, error message print}}</pre><br><p><p><span style="font-size:14px">Does it feel like it's a simple bright? Say so much, let's take a closer look at the Code.</span></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">As previously mentioned, there are two ways of using the Framework:</span></p></p><p><p><span style="font-size:14px">The first is to copy the latest jar from the <span style="color:#ff0000">releases</span> package to the Application's <span style="color:#3333ff">Libs</span> Directory</span></p></p><p><p><span style="font-size:14px">The second is to copy the project source in the <span style="color:#ff0000">library</span> to your Application's <span style="color:#3333ff">src</span> directory (this is the second Way)<br><br>The following is a simple usage of asynchttpclient, which is to create a request</span></p></p><p><p><span style="font-size:14px"></span></p></p><pre name="code" class="java"><pre name="code" class="java">Asynchttpclient client = new Asynchttpclient (); client.get ("http://www.google.com", new Asynchttpresponsehandler () { @Override public void onsuccess (String response) { System.out.println (response); }});</pre></pre><br>Note: the framework can perform a variety of network requests, including<span style="color:#ff0000"><span style="color:#ff0000"> <strong>get</strong>,<strong>put</strong>,<strong>post</strong>,<strong>head</strong>,<strong>delete</strong> </span></span>。 The introduction of different requests, we do not understand the information can be consulted to understand the relevant differences, here is not introduced.<br><br><p><p></p></p><p><p><span style="font-size:14px">We are dealing with the <span style="color:#3333ff">asynchttpclient</span> class, where the two lines of code appear when the request is executed:</span></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Genericdatamanager Mdatamanager = genericdatamanager.getinstance ();//general Network Management class Mdatamanager.datarequest (0, Constants.REQUEST.GET, requesturl.url_login, mparams,new resultparser (), this);//perform Network requests</pre></pre><br><p><p></p></p><p><p><span style="font-size:14px">What the hell is <span style="color:#ff0000"><strong>genericdatamanager</strong></span> ?</span></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">This class is a generic data request class for encapsulation, given this class, together with annotations you can learn:</span></p></p><p><p> </p> </p><pre name="code" class="java">/******************************************************************************* * * Copyright (c) Weaver Info Tech Co. LTD * * DataManager * * * * * * App.backend.manager.DataManager.java * for accessing data on the server * * @author: Gao_chun * @since: Jul 23, 20 * @version: 1.0.0 * * @changeLogs: * 1.0.0:first created this class. * ******************************************************************************/package Org.gaochun.android.http.manager;import Java.io.file;import Org.apache.http.header;import Org.gaochun.android.http.asynchttpclient;import Org.gaochun.android.http.requestparams;import Org.gaochun.android.http.network.irequestcallback;import org.gaochun.android.http.network.RequestCallBack; Import Org.gaochun.model.result;import Org.gaochun.parser.abstractparser;import Org.gaochun.utils.log;import Android.content.context;import android.os.handler;import android.os.looper;/** * @author Gao_chun * General Data communication class, Data that does not involve authentication and Authorization. * task of this class: gets the data object by the corresponding Parameter. * This class does not involve URL Addresses. */public class Genericdatamanager { private static final String TAG = GenericDataManager.class.getSimpleName (); private static Genericdatamanager sinstance; Private final String mserverhost;//server address prefix private final Handler mhandler;//perform asynchronous callback Handler private static ASYNCHTTPC Lient client;//asynchttpclient object//set Timeout Time static{client = new Asynchttpclient (); Initializes the Asynchttpclient object client.settimeout (6 * 1000); Set time-out (important)}//singleton public synchronized static Genericdatamanager getinstance () {if (sinstance = = Null) { LOG.E (TAG, "configmanager.initiate Method not called in the application."); }//else Ignored. Return sinstance; }//need to initialize public static void Initialize (Context applicationcontext, String serverhost) in Application {sinstan CE = new Genericdatamanager (applicationcontext, serverhost); } private Genericdatamanager (Context applicationcontext, String serverhost) {//initialize handler for execution of task m in the main thread Handler = newHandler (looper.getmainlooper ()); Initialize server address Mserverhost = serverhost; }/** * This method encapsulates the network data request and data resolution * and passes in the callback interface * @param requestid Request ID * @param requesttype request type (here, based on the constants passed in Get request and Post Request) * @param urlstring request URL * @param mparams request parameter * @param parser general Data parsing abstract parser * @param Mcallback Custom Interface callback */private Requestcallback Mrequestcallback;//the abstract class inherits Asynchttpresponsehandler and overrides the callback method public <T> void datarequest (final int requestid,string requesttype,string urlstring,requestparams mparams, Final abstractparser<t> mparser,final irequestcallback mcallback) {log.i (TAG, "url:--->" +mserverh OST + File.separator + urlstring); The callback if the request data starts before the IF (mcallback! = Null) {mhandler.post (new Runnable () {@Override public void run () {mcallback.onrequeststart (requestid); } }); }//else ignored Instantiate callback Object mrequestcallback = new Requestcallback () {@Override public void onsuccess ( int statusCode, header[] headers, byte[] responsebody) {string data = new String (responsebody);//get Data results LOG.D (TAG, "server Fetch data:" +data); Final result<t> Result = Mparser.parse (data);//parse class If (Result! = Null) {//return The RequestID + statusCode + result mcallback.onrequestsuccess (requestid,statuscode,result);//return request succeeds and resolves The completed data Callback}//else Ignored. } @Override public void OnStart () {if (mcallback! = Null) {mCall Back.onrequeststart (requestid); }//else ignored} @Override public void onfailure (int statusCode, header[] headers, byte[] responsebody, throwable error) {if (mcallback! = null) { Mcallback.onrequesterror (requestid,error); }//else ignored}}; Switch the specific request method according to the incoming RequestType (note: JDK1.7 in switch () supports string constants) switch (requesttype) {case constants.reque St. GET:client.get (mserverhost + file.separator + urlstring, mparams,mrequestcallback); Break Case Constants.REQUEST.POST:client.post (mserverhost + file.separator + urlstring, Mparams,mrequestcallback ); Break Default:client.get (mserverhost + file.separator + urlstring, mparams,mrequestcallback); Break } }}</pre><br><span style="font-size:14px"><span style="font-size:14px">What we need to note is the parameters passed in the method, and the generic <T> is Used:</span></span><p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">/** * This method encapsulates the network data request and data resolution * and passes in the callback interface * @param requestid Request ID * @param the RequestType request type (where only the get is provided based on the constants passed In) Request and Post Request) * @param urlstring request URL * @param mparams request parameter * @param parser general Data Parsing abstract parser * @ param Mcallback Custom interface callback */public <T> void datarequest (final int requestid,string requesttype,string Urlstrin G,requestparams mparams, final abstractparser<t> mparser,final irequestcallback Mcallback)</pre></pre><p><p></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">The request parameter, request type, Request url, parser, callback, Pass in this method to handle, callback succeeds directly fetch data</span></p></p><p><p><span style="font-size:14px"><br></span></p></p><br><span style="font-size:14px"><span style="font-size:14px">if the project needs to use the Avatar upload, download and other functions,</span></span><span style="font-size:14px; color:rgb(0,0,153)"><span style="font-size:14px; color:rgb(0,0,153)">android-async-http</span></span><span style="font-size:14px">the <span style="font-size:14px">corresponding method has been provided in the project, and you can encapsulate the method yourself in the class. </span></span><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">squeeze time to tidy up this article, the purpose is to give you a simple introduction to the use of the framework, so that interested friends have some understanding, the next blog will give you detailed</span> <span style="font-size:14px">Introduction</span> <span style="color:#ff0000; font-size:14px">datarequest</span> <span style="font-size:14px">abstract parsing class and request parameter encapsulation in the</span> <span style="color:#ff0000; font-size:14px">requestparameterfactory</span> <span style="font-size:14px">class, and of course it needs to be sorted Out.</span> <span style="font-size:14px">Source Code</span> <span style="font-size:14px">after the sharing of learning for EVERYONE. </span></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px">Thank you for your attention, if you feel there is a need to improve the place or good ideas, we welcome your Comments.</span></p></p><p><p><br></p></p> <blockquote style="margin:0 0 0 40px; border:none; padding:0px"> <blockquote style="margin:0 0 0 40px; border:none; padding:0px"> <p><span style="font-size:14px"><span style="color:rgb(255,0,0); font-family:宋体; font-size:18px; line-height:28px; text-indent:36px">@remark: This series of blog is forbidden to reprint</span></span></p> </blockquote> </blockquote><p><p><span style="font-size:14px"><br></span></p></p><p><p><span style="font-size:14px"><br></span></p></p><p><p>Home Car Wash app---android Client Development Network Framework encapsulation Introduction (i)</p></p></span>

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.