First, preface
Recently learned HTTP framework.
This framework is currently written for learning purposes only, and is needed for continuous optimization in projects.
to get data from a server or a network, and display it on the UI, the operation of the network request cannot be placed in the UI thread, and Android has encapsulated the Asynctask class for asynchronous request operations, so the HTTP framework is based on Asynctask.
Ii. main categories of the framework
Define request class, define URL, server return data, POST request params, download progress and other parameters.
Define the Httputil class to encapsulate the HTTP request code. Define the Execute () method inside, which determines whether it is a get or post, and then goes to the call get (), post () method. The required parameters for post () requests are set in request.
In Asynctask, the Doingbackground () method, execute HTTP, writes the returned data to memory into a string return, and if the data is large, it can be stored in a file, returning the path and processing it in a different callback.
Iii. Framework Construction
1. First, we set up the Httpclientutil.java class to handle HTTP GET and post:
/** * @author Mr Fu */public class Httpclientutil {/** * Execute HTTP method, request set requested type * @param requests * @return * @throws exce ption */public static HttpResponse Excute (Request request) throws Exception{switch (Request.requestmethod) {case GET: return get (Request), Case Post:return POST (request);d efault://There is no DELETE and PUT operation defined here throw new IllegalStateException ("You Doesn ' t define this Requestmethod ");}} private static HttpResponse get (Request request) throws Exception {HttpClient client = new Defaulthttpclient (); HttpGet get = new HttpGet (request.url); AddHeader (get, request.headers);//Return results are placed on the previous layer for processing httpresponse response = Client.execute (get); return response;} private static HttpResponse post (Request request) throws Exception {HttpClient client = new Defaulthttpclient (); HttpPost post = new HttpPost (Request.url), AddHeader (post, request.headers),//post request parameter is defined in requests, if empty, there is no define if ( Request.entity = = null) {throw new IllegalStateException ("You forget to set post content to the Httpost");} else {post.Setentity (request.entity);} HttpResponse response = Client.execute (post); return response;} /** * Requests Header * @param request * @param headers */public static void AddHeader (Httpurirequest request, map<string, STRING&G T Headers) {if (headers! = null && headers.size () > 0) {for (entry<string, string> Entry:headers.entrySet ( ) {Request.addheader (Entry.getkey (), Entry.getvalue ());}}} 2. In the code above The request.java class is defined as follows:
/** * @author Mr Fu */public class Request {public enum Requestmethod{get,post,delete,put}requestmethod requestmethod;pub LIC String url;/** * HTTP request parameter type, including form, String, byte etc */public httpentity entity;public map<string, string> headers;p Ublic static final String ENCODING = "UTF-8";/** * Set callback interface, Onsuccess and Onfilure methods in this interface need to be reflected in the UI thread */public icallback Callba Ck;private requesttask task;public Request (String URL, Requestmethod method) {This.url = Url;this.requestmethod = method; }public void Setentity (arraylist<namevaluepair> forms) {try {entity = new urlencodedformentity (forms, ENCODING);} catch (Unsupportedencodingexception e) {e.printstacktrace ();}} public void setentity (String postcontent) {try {entity = new stringentity (postcontent, ENCODING);} catch ( Unsupportedencodingexception e) {e.printstacktrace ();}} public void setentity (byte[] bytes) {entity = new bytearrayentity (bytes);} /** * Sets the callback method to define the method in the UI thread that requires a request to be returned * @param callback */public void Setcallback (Icallback callback) {This. callback = callback;} /** * UI Thread, execute this method, open a asynctask, note asynctask each use must re-*/public void execute () {task = new requesttask (this); Task.execute ();}}3. Icallback Interface:
public interface Icallback {void onfilure (Exception result); void onsuccess (Object result);/** * The HttpResponse from the server is parsed, and after parsing is completed, it is returned to the UI thread */object handle (HttpResponse response);}
4. Requesttask inherits from Asynctask, makes HTTP requests at Doinbackground, and parses the data results returned by the HTTP request, with the following code:
/** * @author Mr fu * @version create time:2014 May 17 pm 2:19:39 */public class Requesttask extends Asynctask<object, Integer, object& Gt {Private request Request;public Requesttask (Request request) {super (); this.request = Request;} @Overrideprotected object Doinbackground (Object ... params) {try {HttpResponse response = Httpclientutil.excute (Request );//response parsing code into the corresponding class, corresponding to the Binddata method in handle return Request.callback.handle (response);} catch (Exception e) {return e;}} @Overrideprotected void OnPostExecute (Object result) {Super.onpostexecute (result); if (result instanceof Exception) {// Failed Request.callback.onFilure ((Exception) result);} else {//Success request.callback.onSuccess (result);}}}
5. Abstractcallback.java the handle method of implementing interface icallback in this class, the main function of this method is to parse the HttpResponse returned by HTTP, if the return status code is 200, The next process is done, the saved path is set, the data returned by HTTP is written to the file first, and then the file is read back to doinbackground (doinbackground
/** * @author Mr fu */public abstract class Abstractcallback implements icallback{/** * file stored path */public String Path;privat e static final int io_buffer_size = 4*1024; @Overridepublic Object handle (HttpResponse response) {//file, JSON, XML, image, Stringint StatusCode = -1;inputstream in = null;try {httpentity entity = response.getentity (); statusCode = Response.getst Atusline (). Getstatuscode (); switch (statusCode) {case HttpStatus.SC_OK:if (textutil.isvalidate (path)) {// Writes the data returned by the server to the file FileOutputStream fos = new FileOutputStream (path); if (entity.getcontentencoding () = null) {String encoding = Entity.getcontentencoding (). GetValue (); if (encoding! = NULL && "gzip". Equalsignorecase (encoding)) { in = new Gzipinputstream (Entity.getcontent ());} if (encoding! = NULL && "Deflate". Equalsignorecase (encoding)) {in = new Inflaterinputstream (Entity.getcontent () );}} else {in = Entity.getcontent ();} Byte[] B = new Byte[io_buffer_size];int read;while ((read = In.read (b))! =-1) {//TODO UpdatE Progressfos.write (b, 0, read);} Fos.flush (); Fos.close (); In.close ();//After writing the file, the data is read from the file and returned directly to the object return Binddata (path); else {//need to return an object, not a data stream, so you need to parse the return CONTENT;//2 in the data//corresponding stringcallback returned by the server. Call Bindatareturn Binddata ( Entityutils.tostring (entity));} Default:break;} return null;} catch (ParseException e) {//None of these exception handling operations, subsequent articles will be processed} catch (IOException e) {}return null;} /** * Data is put into different callback to handle */protected Object Binddata (String content) {//stringcallback, etc. implemented in method return null;} /** * If you want to deposit to a file, set the file path */public abstractcallback setpath (String path) {This.path = Path;return this;}}6. Stringcallback.java The current code, only the callback is implemented:
Public abstract class Stringcallback extends Abstractcallback {@Overrideprotected Object binddata (String content) {// If the path exists, re-tell the data to read from the file if (textutil.isvalidate (path)) {return ioutiliteies.readfromfile (path);} return content;}}
7. The Textutil.java class used in the
public class Textutil {public static Boolean isvalidate (String content) {return content! = NULL &&! "". Equals (Content.trim ());} public static Boolean isvalidate (Arraylist<namevaluepair> content) {return content! = NULL && content.size () > 0;}}
8. The following methods are specifically called in the UI thread:
private void RequestString () {//Set save path string path = Environment.getexternalstoragedirectory (). GetAbsolutePath () + File.separator + "Mrfu_http.txt"; Request Request = new request ("http://www.baidu.com", Requestmethod.get), Request.setcallback (new Stringcallback () {@ overridepublic void onsuccess (Object result) {Mtestresultlabel.settext (String) result); @Overridepublic void Onfilure (Exception result) {result.printstacktrace ();}}. SetPath (path)); Request.execute ();}
where Mtestresultlabel is TextView
Here is just one of the most preliminary framework, you can see a lot of operations are not processed, such as JSON parsing, download progress update, cancel the request at any time, the return of the object preprocessing operation, and exception handling are not specific to implement, and some of the code structure is not perfect, If you are working directly with object.
Later in the article will be the framework of the step-by-night, including the above mentioned.
Special thanks to stay teacher for his help in this. Let me take the first step in the framework to learn this piece of real deal!
SOURCE Download: http://download.csdn.net/detail/fu222cs98/7377683
Welcome reprint, Reprint Annotated source, thank you
Mr FU: Stay