Android Network Framework android-async-http

Source: Internet
Author: User
Tags http authentication

Android Network Framework android-async-http

 

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, the anonymous callback response function sends the Request Requests in other threads rather than the UI thread. The thread pool management restricts concurrent resources. You can customize the GET/POST parameters. Multiple File Upload Methods: JSON data upload Request Retry Mechanism. parse Multiple Data Formats support persistent storage cookies support SAX parsing support multiple content and language encoding formats, not just UTF-8

More features: android-async-http

2. Use of Android-async-http Like all third-party libraries, we need to add them to our project.: You can directly download the latest. jar package (android-async-http.jar), you can also clone it from github to local: android-async-http
To directly download the. jar package, add it to the ProjectlibsFolder, right-click the jar package, and select Add As Library: If it is a clone project, you still need to compile it into a jar package, and then add it to the project according to step 3.The compilation process is as follows:
First, go to the clone android-async-http directory, and then execute the following command on the command line:
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 http response 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 3 4 ...} @ 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 also add and store cookies locally, create Cookie objects first, 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 to a Map object by using a key value.
  
   
Map = new HashMap
   
    
(); 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::

Based on your needs githubWebsites looking for more popular frameworks; be familiar with the features and Use Cases of the frameworks you have selected and Defects. Introduce the corresponding jar package into the project. Follow the official examples to learn the basic usage. Do more exercises and be familiar with use cases. Study the source code and rewrite the framework to meet your needs.

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 ~~

 

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.