Android Network Request library: Android-async-http Open source Framework
Previously, there was an article describing how the client requested the server-side-post. Today, we introduce an open source Library-android-async-http library for a request server.
1. Concept:
This network request library is an asynchronous network request processing library based on the Apache HttpClient Library, which is based on the non-UI thread of Android and processes the request result through the callback method (anonymous inner Class).
2. Features:
(1).Handles asynchronous HTTP requests and processes callback results through anonymous inner classes
* * (2). **http asynchronous requests are located on non-UI threads and do not block UI operations.
(3).Processing of concurrent requests through the thread pool handles file uploads, downloads, and response results are automatically packaged in JSON format.
3. Description of the corresponding core class:
(1). Asynchttpresponsehandler:A class that requests to return a custom message that handles success, failure, start, completion, and so on.
(2). Binaryhttpresponsehandler: Subclass of Asynchttpresponsehandler. The class is a byte stream that returns the processing class. Used to process pictures and so on.
(3). Jsonhttpresponsehandler: Subclass of Asynchttpresponsehandler. This is a class used by the server to communicate with the client using JSON data. The parameters of the client Pull server are JSON data types, and the data returned to the client by the server is also of the JSON data type.
(4). Requestparams: Encapsulates the class for parameter handling. Encapsulates the parameters of the client request in the class.
(5). Asynchttpclient: The class that the asynchronous client requested.
(6). Synchttpclient: Synchronizes the class requested by the client. The subclass of the asynchttpclient.
Note: The Httputil class mainly lists the get methods that we use most often, and the class is called where it is to be used.you need to add a Android-async-http-1.4.7.jar file package.
The code is as follows:
(1). Asyncjsonutilget.java
PackageCom.chengdong.su.util.get;ImportOrg.apache.http.Header;ImportOrg.json.JSONException;ImportOrg.json.JSONObject;ImportAndroid.content.Context;ImportAndroid.widget.Toast;ImportCom.loopj.android.http.JsonHttpResponseHandler;ImportCom.loopj.android.http.RequestParams;/** * Asynchronous Request Server * * @author SCD * */ Public class asyncjsonutilget { Private Static FinalString URL ="";PrivateContext Mcontext;/** * Construction Method * * @param mcontext * * Public Asyncjsonutilget(Context Mcontext) {Super(); This. Mcontext = Mcontext; }/** * Email registration * * Public void Emailregister(string email, string password, string username) {Requestparams params =NewRequestparams (); Jsonobject Jsonobject =NewJsonobject ();Try{Jsonobject.put ("Email", email); Jsonobject.put ("Password", password); Jsonobject.put ("username", username); }Catch(Jsonexception e) {E.printstacktrace (); } params.put ("Jsonobject", Jsonobject);//Get request modeHttputil.get (URL, params,NewJsonhttpresponsehandler () {@Override Public void onfailure(intStatusCode, header[] headers, throwable throwable, Jsonobject errorresponse) {Super. OnFailure (StatusCode, headers, throwable, errorresponse); Toast.maketext (Mcontext,"Register failed!", Toast.length_short). Show (); }@Override Public void onsuccess(intStatusCode, header[] headers, jsonobject response) {String ErrorCode = Response.optstri Ng"ErrorCode");//indicates successful request if(Errorcode.equals ("0") {Toast.maketext (Mcontext,"Registered successfully", Toast.length_long). Show ();///Response: The returned data is in this parameter and is implemented according to business requirements}Else{Super. onsuccess (StatusCode, headers, response); } } }); }}
(2). Httputil.java Tool Class: Note: You need to add a jar package
PackageCom.chengdong.su.util.get;ImportJava.io.IOException;ImportJava.io.UnsupportedEncodingException;ImportJava.net.MalformedURLException;ImportJava.net.URL;ImportJava.net.URLConnection;ImportJava.util.List;ImportJava.util.Map;ImportJava.util.Set;ImportAndroid.content.Context;ImportAndroid.net.ConnectivityManager;ImportAndroid.net.NetworkInfo;ImportCom.loopj.android.http.AsyncHttpClient;ImportCom.loopj.android.http.AsyncHttpResponseHandler;ImportCom.loopj.android.http.BinaryHttpResponseHandler;ImportCom.loopj.android.http.JsonHttpResponseHandler;ImportCom.loopj.android.http.RequestParams; Public class httputil { Public Static FinalString status_network ="Network_available";Private StaticAsynchttpclient client =NewAsynchttpclient ();Static{Client.settimeout (11000); } Public Static void Get(String urlstring, Asynchttpresponsehandler Res) {Client.get (urlstring, RES); } Public Static void Get(String urlstring, requestparams params, asynchttpresponsehandler res) {Client.get (urlstring, params, res); } Public Static void Get(String urlstring, Jsonhttpresponsehandler Res) {Client.get (urlstring, RES); } Public Static void Get(String urlstring, requestparams params, jsonhttpresponsehandler res) {Client.get (urlstring, params, res); } Public Static void Get(String ustring, Binaryhttpresponsehandler Bhandler) {Client.get (ustring, Bhandler); } Public StaticAsynchttpclientgetclient() {returnClient } Public Static Boolean isnetworkconnected(Context context) {if(Context! =NULL{Connectivitymanager Mconnectivitymanager = (connectivitymanager) context. Getsystemservi CE (context.connectivity_service); Networkinfo mnetworkinfo = Mconnectivitymanager. Getactivenetworkinfo ();if(Mnetworkinfo! =NULL) {returnMnetworkinfo.isavailable (); } }return false; }//Get the file name from URLConnection Public StaticStringGetFileName(String URL) {String FileName =NULL;BooleanIsOK =false;Try{URL Myurl =NewURL (URL); URLConnection conn = Myurl.openconnection ();if(conn = =NULL) {return NULL; } map<string, list<string>> HF = Conn.getheaderfields ();if(HF = =NULL) {return NULL; } set<string> key = Hf.keyset ();if(Key = =NULL) {return NULL; } for(String Skey:key) {List<string> values = Hf.get (skey); for(String value:values) {String result;Try{result = value;intLocation = Result.indexof ("FileName");if(Location >=0) {result = result.substring (location +"FileName". Length ()); result = Java.net.URLDecoder. Decode (Result,"Utf-8"); result = Result.substring (Result.indexof ("\"") +1, Result.lastindexof ("\"")); FileName = result. Substring (Result.indexof ("=") +1); IsOK =true; } }Catch(Unsupportedencodingexception e) {E.printstacktrace (); } }if(IsOK) { Break; } } }Catch(Malformedurlexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }returnFileName; }}
Android-async-http A detailed explanation of the open source framework