Introduction to the Android asynchronous HTTP framework and its implementation principles

Source: Internet
Author: User

in the previous articles, " Android uses get to submit data to server "Android uses post to submit data to server" Android uses httpclient submit data to server describes two ways to submit data to the server on Android

This article will introduce another method based on frame android-async-http to realize

Android-async-http is a powerful network request library, which is based on the Apache HttpClient Library of an asynchronous network request processing library, network processing is based on the Android non-UI thread, the callback method to process the request results. Android-async-http is a powerful third-party open source Network request Library

Official Source: Https://github.com/loopj/android-async-http

Official website Tutorial: http://loopj.com/android-async-http/

New project, first on GitHub: https://github.com/loopj/android-async-http/tree/1.4.0

Download the appropriate zip file, unzip the COM folder in src to the SRC directory of the project

The following is the framework android-async-http, with the following code:

 Packagecom.wuyudong.asynchttp;ImportJava.net.URLEncoder;Importcom.loopj.android.http.AsyncHttpClient;ImportCom.loopj.android.http.AsyncHttpResponseHandler;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.view.View;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); }     Public voidClick (View view) {//User name password submitted to serverAsynchttpclient client =Newasynchttpclient (); String Path= "Http://169.254.168.71:8080/web/LoginServlet?username=" + urlencoder.encode ("Wuyudong") + "&password= "+ Urlencoder.encode (" 123 "); Client.get (Path,NewAsynchttpresponsehandler () {@Override Public voidonsuccess (String content) {//TODO auto-generated Method Stub                Super. onsuccess (content); Toast.maketext (mainactivity. This, "The request was successful! ", 0). Show (); } @Override Public voidonfailure (throwable error, String content) {//TODO auto-generated Method Stub                Super. OnFailure (Error, content); Toast.maketext (mainactivity. This, "The request failed! ", 0). Show ();    }        }); }}

You can see that the code volume is reduced a lot

Below to implement a compact version of the asynchronous framework

New Project

Asynchttpclient.java

 Packagecom.wuyudong.AsyncClient;Importjava.io.IOException;ImportJava.io.InputStream;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.ClientProtocolException;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpGet;Importorg.apache.http.impl.client.DefaultHttpClient;ImportAndroid.os.Message; Public classasynchttpclient { Public voidGetFinalString Path,FinalMyHandler MyHandler) {        NewThread () {@Override Public voidrun () {HttpClient client=Newdefaulthttpclient (); HttpGet HttpGet=Newhttpget (path); Try{HttpResponse response=Client.execute (HttpGet); InputStream is=response.getentity (). getcontent (); String content=Streamtools.readinputstream (IS); //Successful ExecutionMessage msg =NewMessage (); Msg.what= 0; Msg.obj= "Request Succeeded";                Myhandler.sendmessage (msg); } Catch(Exception e) {e.printstacktrace (); //Execution failedMessage msg =NewMessage (); Msg.what= 1; Msg.obj= "Request Failed";                Myhandler.sendmessage (msg);    }}}.start (); }}

Mainactivity.java

 Packagecom.wuyudong.AsyncClient;ImportJava.net.URLEncoder;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.view.View;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); }     Public voidClick (View view) {//1. Turn on the child thread to execute an HTTP request in the background execution on the child thread//2. Notify UI interface after child thread finishes executingasynchttpclient Client=Newasynchttpclient (); String Path= "Http://169.254.168.71:8080/web/LoginServlet?username=" + urlencoder.encode ("Wuyudong") + "&password= "+ Urlencoder.encode (" 123 "); Client.get (Path,NewMyHandler () {@Override Public voidonfailure (String content) {Toast.maketext (mainactivity. This, content, 1). Show (); Super. OnFailure (content); } @Override Public voidonsuccess (String content) {Toast.maketext (mainactivity. This, content, 0). Show (); Super. onsuccess (content);    }        }); }}

Myhandler.java

 Packagecom.wuyudong.AsyncClient;ImportAndroid.os.Handler;ImportAndroid.os.Message; Public classMyHandlerextendsHandler { Public voidonfailure (String content) {} Public voidonsuccess (String content) {} @Override Public voidhandlemessage (Message msg) {String content=(String) msg.obj; Switch(msg.what) { Case0: onsuccess (content);  Break;  Case1: onfailure (content);  Break; default:             Break; }        Super. Handlemessage (msg); }}

Streamtools.java

 Packagecom.wuyudong.AsyncClient;ImportJava.io.ByteArrayOutputStream;ImportJava.io.InputStream; Public classStreamtools {/*** Convert the contents of the input stream into a string * *@paramis *@return     */     Public StaticString Readinputstream (InputStream is) {Try{bytearrayoutputstream BAOs=NewBytearrayoutputstream (); intLen = 0; byte[] buffer =New byte[1024];  while(len = is.read (buffer))! =-1) {baos.write (buffer,0, Len);            } is.close ();            Baos.close (); byte[] result =Baos.tobytearray (); String Str=NewString (Result); //try to parse the string inside result            if(Str.contains ("gb2312")) {                return NewString (Result, "gb2312"); } Else if(Str.contains ("Utf-8")){                returnstr; } Else {                return NULL; }                        //return new String (result, "gb2312");}Catch(Exception e) {e.printstacktrace (); return NULL; }    }}

Introduction to the Android asynchronous HTTP framework and its implementation principles

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.