Android Network Framework android-async-http, androidasynchttp

Source: Internet
Author: User

Android Network Framework android-async-http, androidasynchttp

Reprinted please indicate the source: mingsang Android

This is the last part of the Android network framework series ~~,
This article mainly introduces the use of the third-party library android-async-http. Later, as the end of the Android network framework series, it summarizes how to learn and use third-party frameworks during development!

1. Introduction to Android Asynchronous Http Client

Android-async-http encapsulates the top-level implementation of HttpClient, and all requests initiated by it run in different threads of the UI thread, however, the callback processing logic is the same as the callback logic that uses Handler to send message processing. You can also run it in the Service thread or background thread.

Features:

  • Asynchronous HTTP request, anonymous callback Response Function
  • Send a Request in other threads rather than the UI thread
  • Requests uses the thread pool to manage and limit concurrent Resources
  • You can customize GET/POST parameters.
  • Multiple File Upload Methods
  • Upload JSON data
  • Request Retry Mechanism
  • Parse Multiple Data Formats
  • Supports persistent storage of cookies
  • Support for SAX Parsing
  • Supports multiple content and language encoding formats, not just UTF-8

More features: android-async-http

2. Use of Android-async-http
android update project -pant jar

2.Basic usage of android-async-http:
We first need to createAsyncHttpClientInstance, and then use it to initiate a Request

AsyncHttpClietn client = new AsyncHttpClient (); client. get ("http://www.baidu.com", new AsyncHttpResponseHandler () {@ Override public void onStart () {// called before Request initiation} @ Override public void onSuccess (int statusCode, header [] headers, byte [] response) {// call when the response is correct, statusCode = 200, headers indicates the response http Header, response: response Return Value} @ Override public void onFailure (int statusCode, Header [] heards, byte [] errorResponse, Throwable e) {// call when the response is incorrect: statusCode = 401 \ 403 \ 404 \...} @ Override public void onRetry (int retryNo) {// call upon request retry }});

Recommended usage:Create static Http Client;

Like the Volley framework, we should create a separate class to initialize the code that I can need so that we can hold some objects globally. Here we encapsulate what we need in a static Client class. You can write a custom Client Class Based on your needs. For details, refer to the API: AsyncHttpClient, RequestParams and AsyncHttpResponseHandler.

Public class MyCLient {private static final String BASE_URL = "http://www.baidu.com"; // create a static client private static AsyncHttpClient client = new AsyncHttpClient (); // override the get, post and other methods public static get (String url, RequestParams params, AsyncHttpResonseHandler responseHand) {client. get (url, params, respnseHand)} public static post (String url, RequestParams params, aAsyncHttpResponseHandler responseHand) {client. post (url, params, responseHand) ;}// you can call it as needed, MyClient. get (url, params, new AsyncHttpResonseHandler (){...});

3.Cookie storage:By using PersistentCookieStore, it implements the CookieStore interface in HttpClient, automatically stores cookies to local SharedPerferences, and is often used to store user login information.

AsyncHttpClient client = new AsyncHttpClient (); PersistentCookieStore cookieStore = new PersistentCookieStore (context); client. setCookieStore (cookieStore); // Of course, you can add and store cookies locally, create Cookie objects, and then add BasicClientCookie myCookie = new BasicClientCOokie ("cookieuser ", "hh"); myCookie. setViersion (1); myCookie. setDomain ("www.my.com"); myCookie. setPath ("/"); client. addCookie (myCookie );

4.Add the GET/POST parameter to the Request:The RequestParams class is required,
There are several ways to create a table:

RequestParams params = new RequestParams ("username", "coder"); // or RequestParams params = new RequestParams (); params. put ("username", "coder"); // You can also add a HashMap <String, String> Map = new HashMap <String, String> () to a map object by using a key value (); map. put ("username", "coder"); RequestParams params = new RequestParams (map );.... // Do you still remember the get () and post () methods previously written? RequestParams is its second optional parameter client. get (url, params, new AsyncHttpResponseHandler (){..});

5.Upload a file through RequestParams: As we have learned how to try RequestParams, we can use the following methods to upload a file:

Upload through input stream:

    InputStream myInputStream = blah;    RequestParams params = new RequestParams();    params.put("secret_passwords", myInputStream, 

Using passwords.txt ");

Upload through a file object:

    File myFile = new File("/path/to/file.png");    RequestParams params = new RequestParams();    try {        params.put("profile_picture", myFile);    } catch(FileNotFoundException e) {}

Upload through byte array:

    byte[] myByteArray = blah;    RequestParams params = new RequestParams();    params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");

6. download binary files: The FileAsyncHttpResponseHandler class can be used to download binary files such as images.

AsyncHttpClient client = new AsyncHttpClient (); client. get ("www.my.com/movies.jpg", new FileAsyncHttpResponseHandler () {@ Override public void Success (int statusCode, Header [] headers, File response) {// get File }})

So how can we send other types of Json requests? In fact, we can find that we only need to: new JsonHttpResponseHandler (){..}

7.HTTP authentication Request: Webservice usually requires authentication, which can be implemented in the following two ways:

AsyncHttpClient client = new AsyncHttpClient (); // client. setBasicAuth ("username", "password/token"); client. get ("http://www.my.com"); // You can also set a more detailed verification range client. setBasicAuth ("username", "password", new AuthScope ("www.my.com", 80, AuthScope. ANY_REALM); client. get ("http://www.my.com ");

The above is the basic usage of the android-async-http framework. Do not write a specific Demo. For more information, see the API provided on the official website:Android-sync-http API

Summary:

The learning of the Android network framework has come to an end. It mainly introduces the use of Volley, Picasso, and android-sync-http frameworks, I hope it will be helpful to those who are learning Android network programming.

In use, we need to select the desired framework based on our own needs and the characteristics of each framework. In the early stage, we can master the basic usage, in many cases, we should try to study their source code so that they can be used freely in future development.

In fact, after several articles, we can find thatThere are only a few steps to use a third-party framework during development::

Next we will prepare to write an article on practical use of the above framework.Implement a simple APPIf you are interested, follow the Weibo account or public account and update it at any time ~~

References:

Android Asynchronous Http Client

  • Weibo: @ mingsang Android Black History
  • Mailbox: <13141459344@163.com>
  • Personal Homepage: The history of mingsang's victory over Android Wang
  • Public Account: ITBird

Related Article

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.