Home Car Wash App---androidclient introduction of network Framework package (i)

Source: Internet
Author: User
Tags getmessage response code tidy

Introduction to the Home Car wash app---Android Client Development Network Framework package (i)


the previous article gives you a brief introduction to some of the business. Home Car Wash App---Android client development preface and Business Brief introduction , this article introduces you to the network frame frame. I have also learned about some open source network communication architectures. I've probably seen some of the source code. For example, Afinal, Volley, Andbase, Android-async-http , and so on, feel each have their own merits and demerits, they have also encapsulated some simple network architecture, feel that there are a lot of places need attention and optimization. It is not posted here caught dead, interested friends can go to learn the above-mentioned open-source projects, but also to view the previously organized blog:Android Open source Framework (collation) for related learning. Here are just a few more introductions.


The communication framework used in this project isandroid-async-http, and has written a brief introduction to it before. Android-async-http Open Source project introduction and Usage。 As you can easily understand, this project provides a series of encapsulation of data requests based on the schema for the return of the data results.



Here to share my ideas and ideas, and everyone to study together. This can be understood for network requests that are made. Request ---> include ( request, request in, request fails. Request ends , and the server responds successfully to the data. Parse the data results. Storage and other processing. This is the main framework. The individual feels that it is not well enough to be able to return to the request data where it can be processed and further optimized. How about that?


I think so, after making the request. The data obtained is expected to be parsed, rather than parsed from the returned results. Other words. after the request is complete , The result of the data is parsed, and the returned result is already directly the object to use. in this case, the entire request resolution is much more convenient.


So what exactly is the effect? Let's look at a sample login request example below:

private void Login (String name,string pwd) {Genericdatamanager Mdatamanager = genericdatamanager.getinstance ();// General network Management class Requestparams Mparams = Requestparameterfactory.getinstance (). Login (name, pwd);// Request Parameters Management class Mdatamanager.datarequest (0,constants.request.get, Requesturl.url_login, Mparams,new ResultParser (), this); /Run Network Request}


Only 3 lines of code are required to initiate a request. So how do you use it in detail in your Activity? We've thrown out a irequestcallback request Response callback interface, which provides three callback methods. For Activity implementation, namely:

/** * 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}


Note:RequestID is the request ID, in order to differentiate which request. For example: one Activity needs two or many other requests, how to distinguish the detailed request in the callback? Use RequestID to differentiate.

The data can be obtained simply by implementing the interface in the Activity and implementing the Detailed method:

/******************************************************************************* * * 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//here to display 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 printing Information}}

Does it feel like it's a simple bright? Say so much, let's take a closer look at the code.


As previously mentioned, there are two ways of using the framework:

The first is to copy the latest jar from the releases package to the app's Libs folder

The other is to copy the project source code in the library into your application's src folder (this is another way)

The following is a simple usage of asynchttpclient. That is, create a request

Asynchttpclient client = new Asynchttpclient (); Client.get ("http://www.google.com", new Asynchttpresponsehandler () {    @Override public    void onsuccess (String response) {        System.out.println (response);    }});

Note: The framework can run multiple network requests, including get, put, post, head, delete 。 The introduction of different requests, we do not understand the ability to consult the information to understand the relevant differences, here is not introduced.



We are dealing with the asynchttpclient class. These two lines of code appear when you run a request above:

Genericdatamanager Mdatamanager = Genericdatamanager.getinstance ();//General Network Management class Mdatamanager.datarequest (0, Constants.REQUEST.GET, Requesturl.url_login, Mparams,new resultparser (), this);//Run Network request

What the hell is genericdatamanager ?


This class is a generic data request class for encapsulation, the following gives this class, combined with the gaze that you can learn:

/******************************************************************************* * * Copyright (c) Weaver Info Tech  Co. LTD * * DataManager * * * * * App.backend.manager.DataManager.java * To access data on the server * * @author: Gao_chun * @since: Jul 23, * @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 number of parameters. * 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;//run asynchronous callback Handler private static Asyncht   Tpclient Client;//asynchttpclient Object//Set timeout time static{client = new Asynchttpclient ();     Initializes the Asynchttpclient object Client.settimeout (6 * 1000); Set time-out (important)}//Singleton public static Genericdatamanager getinstance () {if (sinstance = = null) {L        OG.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 running task m in the main thread Handler = new Handler(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 only     Get request and POST request) * @param urlstring request URL * @param mparams request Reference * @param parser General Data parsing abstract parser * @param mcallback itself defines the interface callback */private Requestcallback mrequestcallback;//The abstract class inherits Asynchttpresponsehandler and             Wrote a 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:--->" +mserve        RHost + 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 (in                T 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            Finished 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 detailed 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 }    }}

we need to be aware of the parameters that are passed in the method and use generic <T>:

/** * 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 (here, based on the constants passed in, provides only GE T request and POST request) * @param urlstring request URL * @param mparams request parameter * @param parser general Data parsing abstract parser * @param mcallback itself defines the interface callback */public <T> void datarequest (final int requestid,string requesttype,string URLSTR Ing,requestparams Mparams,            final abstractparser<t> mparser,final irequestcallback mCallback)


The request parameter, the request type, the request URL. Parser. Callback, which is processed in this method, the callback succeeds in fetching the data directly



assume that the project needs to use the Avatar upload, download and other functions,android-async-httpThe method has been provided in the project, and you can encapsulate the method yourself in the class.


squeeze the 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 a detailed introduction of datarequest in the abstract parsing class and request for the package of parameters Requestparameterfactory class, of course, also need to tidy up the source code for everyone to share learning.


If you think there are areas or good ideas that need improvement, you are welcome to comment.



Home Car Wash App---Android client development preface and Business Brief introduction

Home Car Wash App---Android Client Development Network Framework Encapsulation Introduction (i)

Home Car Wash App---Android Client Development Network Framework package introduction (b)

Introduction to the project structure of the home car wash app---android client development



"NOTE: Reprint annotated Gao_chun blog http://blog.csdn.net/gao_chun/article/details/46610555"


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Home Car Wash App---androidclient introduction of network Framework package (i)

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.