Android asynchronous Http framework introduction and implementation principle, android framework

Source: Internet
Author: User

Android asynchronous Http framework introduction and implementation principle, android framework

In the previous articles, Android uses get to submit data to the server, Android uses post to submit data to the server, Android uses HttpClient to submit data to the server, and android introduces two types of Android how to submit data to the server

This article introduces another method based on the Framework android-async-http.

Android-async-http is a powerful network request library, which is an Asynchronous Network request processing Library Based on the Apache HttpClient library, network processing is based on non-UI threads of Android, and request results are processed through callback. Android-async-http is a powerful third-party open-source network request library

Official Website source code: https://github.com/loopj/android-async-http

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

Create a project first on github: https://github.com/loopj/android-async-http/tree/1.4.0

Download the corresponding zip file, decompress it, and copy the com folder in src to the src directory of the project.

The following code uses the framework android-async-http:

Package com. wuyudong. asynchttp; import java.net. URLEncoder; import com. loopj. android. http. asyncHttpClient; import com. loopj. android. http. asyncHttpResponseHandler; import android. OS. bundle; import android. app. activity; import android. view. view; import android. widget. toast; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstance State); setContentView (R. layout. activity_main);} public void click (View view) {// submit the user name and password to the server AsyncHttpClient client = new AsyncHttpClient (); String path = "http: // 169.254.168.71: 8080/web/LoginServlet? Username = "+ URLEncoder. encode ("wuyudong") + "& password =" + URLEncoder. encode ("123"); client. get (path, new AsyncHttpResponseHandler () {@ Override public void onSuccess (String content) {// TODO Auto-generated method stub super. onSuccess (content); Toast. makeText (MainActivity. this, "request successful! ", 0 ). show () ;}@ Override public void onFailure (Throwable error, String content) {// TODO Auto-generated method stub super. onFailure (error, content); Toast. makeText (MainActivity. this, "request failed! ", 0). show ();}});}}

We can see that the amount of code is much reduced.

The following describes how to implement a simplified asynchronous framework.

Create a project

AsyncHttpClient. java

Package com. wuyudong. asyncClient; import java. io. IOException; import java. io. inputStream; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpGet; import org. apache. http. impl. client. defaultHttpClient; import android. OS. message; public class AsyncHttpClient {public void get (final String path, final MyHandler myHandler) {new Thread () {@ Override public void run () {HttpClient client = new DefaultHttpClient (); httpGet httpGet = new HttpGet (path); try {HttpResponse response = client.exe cute (httpGet); InputStream is = response. getEntity (). getContent (); String content = StreamTools. readInputStream (is); // Message msg = new Message (); msg. what = 0; msg. obj = "successful request"; myHandler. sendMessage (msg);} catch (Exception e) {e. printStackTrace (); // execution failure Message msg = new Message (); msg. what = 1; msg. obj = "request failed"; myHandler. sendMessage (msg );}}}. start ();}}

MainActivity. java

Package com. wuyudong. asyncClient; import java.net. URLEncoder; import android. OS. bundle; import android. app. activity; import android. view. view; import android. widget. toast; public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} public void click (View view) {// 1. Enable the subthread to execute an htt. P request, which is executed in the background in the sub-thread // 2. After the sub-thread is executed, notify the ui interface AsyncHttpClient client = new AsyncHttpClient (); String path = "http: // 169.254.168.71: 8080/web/LoginServlet? Username = "+ URLEncoder. encode ("wuyudong") + "& password =" + URLEncoder. encode ("123"); client. get (path, new MyHandler () {@ Override public void onFailure (String content) {Toast. makeText (MainActivity. this, content, 1 ). show (); super. onFailure (content) ;}@ Override public void onSuccess (String content) {Toast. makeText (MainActivity. this, content, 0 ). show (); super. onSuccess (content );}});}}

MyHandler. java

package com.wuyudong.AsyncClient;import android.os.Handler;import android.os.Message;public class MyHandler extends Handler {    public void onFailure(String content) {    }    public void onSuccess(String content) {    }    @Override    public void handleMessage(Message msg) {        String content = (String) msg.obj;        switch (msg.what) {        case 0:            onSuccess(content);            break;        case 1:            onFailure(content);            break;        default:            break;        }        super.handleMessage(msg);    }}

StreamTools. java

Package com. wuyudong. asyncClient; import java. io. byteArrayOutputStream; import java. io. inputStream; public class StreamTools {/*** converts the content of the input stream to a String ** @ param is * @ return */public static String readInputStream (InputStream is) {try {ByteArrayOutputStream baos = new ByteArrayOutputStream (); int len = 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 = new String (result); // try to parse the String if (str. contains ("gb2312") {return new String (result, "gb2312");} else if (str. contains ("UTF-8") {return str;} else {return null;} // return new String (result, "gb2312");} catch (Exception e) {e. printStackTrace (); return null ;}}}

 

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.