Android Network Request Library: Android-async-http Open source Framework
A previous article describes the way the client requests server-side-post. Today, we introduce an open source Library-android-async-http library requesting server.
1. Concept:
The network request library is based on an asynchronous network request processing library above the Apache HttpClient Library, which is based on the Android non-UI thread and processes the request results through the callback method (anonymous inner Class).
2. Characteristics:
(1). Process asynchronous HTTP requests and handle callback results through anonymous inner classes
* * (2). **http asynchronous requests are located on a non-UI thread and do not block UI actions.
(3). Through the thread pool processing concurrent request processing file upload, download, response results automatically packaged in JSON format.
3. Introduction of the corresponding core classes:
(1). Asynchttpresponsehandler: Request returns a class that handles custom messages such as success, failure, start, completion, and so on.
(2). Binaryhttpresponsehandler:asynchttpresponsehandler subclass of the class. The class is a byte stream that returns the processed class. For processing pictures and so on.
(3). Jsonhttpresponsehandler:asynchttpresponsehandler subclass of the class. This is the class used by a server to communicate with the client using JSON data. The client requests that the server's parameters are JSON data types, and that the data returned to the client by the server is also the JSON data type.
(4). Requestparams: Encapsulates the class for parameter processing. Encapsulates a client-requested parameter in the class.
(5). Asynchttpclient: Class for asynchronous client requests.
(6). Synchttpclient: Synchronizes the class that the client requests. Asynchttpclient subclass of the class.
Note: Httputil This class mainly lists our commonly used get methods, and it's OK to call the class where you want to use it. You need to add a Android-async-http-1.4.7.jar package.
The code is as follows:
(1). Asyncjsonutilget.java
Package com.chengdong.su.util.get;
Import Org.apache.http.Header;
Import org.json.JSONException;
Import Org.json.JSONObject;
Import Android.content.Context;
Import Android.widget.Toast;
Import Com.loopj.android.http.JsonHttpResponseHandler;
Import Com.loopj.android.http.RequestParams;
/** * Asynchronous Request Server * * @author SCD * * */public class Asyncjsonutilget {private static final String URL = "";
Private context Mcontext;
/** * Construction Method * * @param mcontext/Public asyncjsonutilget (context Mcontext) {super ();
This.mcontext = Mcontext; /** * Mailbox Registration/public void Emailregister (string email, string password, string username) {Requestparams
params = new Requestparams ();
Jsonobject jsonobject = new Jsonobject ();
try {jsonobject.put ("email", email);
Jsonobject.put ("password", password);
Jsonobject.put ("username", username);
catch (Jsonexception e) {e.printstacktrace (); } params.put ("Jsonobject", Jsonobject); Get Request Method Httputil.get (URL, params, new Jsonhttpresponsehandler () {@Override public void onfailure (int StatusCode, header[] headers, throwable throwable, Jsonobject errorresponse) {super.onfailure (statuscod
E, headers, throwable, errorresponse);
Toast.maketext (Mcontext, "Register failed!", Toast.length_short). Show ();
@Override public void onsuccess (int statusCode, header[] headers, jsonobject response) {
String errorcode = response.optstring ("ErrorCode");
Indicates that the request was successful 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
Package com.chengdong.su.util.get;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import java.net.URLConnection;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Set;
Import Android.content.Context;
Import Android.net.ConnectivityManager;
Import Android.net.NetworkInfo;
Import com.loopj.android.http.AsyncHttpClient;
Import Com.loopj.android.http.AsyncHttpResponseHandler;
Import Com.loopj.android.http.BinaryHttpResponseHandler;
Import Com.loopj.android.http.JsonHttpResponseHandler;
Import Com.loopj.android.http.RequestParams;
public class Httputil {public static final String status_network = "network_available";
private static Asynchttpclient client = new Asynchttpclient ();
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 static Asynchttpclient Getclient () {return client; public static Boolean isnetworkconnected {if (context!= null) {Connectivitymanager Mcon
Nectivitymanager = (connectivitymanager) context. Getsystemservice (Context.connectivity_service);
Networkinfo mnetworkinfo = Mconnectivitymanager. Getactivenetworkinfo ();
if (mnetworkinfo!= null) {return mnetworkinfo.isavailable ();
return false; }//From UrlconnectIon gets the file name public static String getfilename (string url) {string fileName = null;
Boolean IsOK = false;
try {URL myurl = new URL (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;
int location = 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;
A catch (Malformedurlexception e) {e.printstacktrace ());
catch (IOException e) {e.printstacktrace ();
return fileName;
}
}
Introduction of Open Source home: http://open.jb51.net/project/app-framework/android-async-http.html