An asynchronous implementation of an Android HTTP network request _android

Source: Internet
Author: User
Tags class definition

Objective

We all know that the response time of network operation is uncertain, all network operations should be handled in an asynchronous operation, and for module decoupling, we want network operations to be handled by specialized classes. All network data sent, data received have some classes to implement, external other modules as long as the call and processing callback function. The call relationship between the external module and the network module can be represented in the following illustration:

The caller can simply create the request object, set the parameters, and initiate requests. The final result is returned by the callback function. The asynchronous task on the right, httpclient creation, parameter parsing, and error handling are all handed over to the network processing module to complete. From this point of view, this network module is in fact a very high repetition of the development work, in order to avoid duplication of the wheel, the following is to introduce our work in the implementation of the network Operation module and the implementation of the corresponding classes.

1. Caller-Side code:

Get or POST request

protected void Dowebtest () {String URL = "HTTP://WWW.TARGET.COM/ABCD";
   try {myhttprequest http = new Myhttprequest (URL);
   If it is a POST request, set. If it is a GET request, do not set the post parameter//http.addpost ("Data", "Testpostvalue"); Post parameter end, GET request, do not add above Addpost code http.addheader ("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9
   , image/webp,*/*;q=0.8 ");
   Http.addheader ("accept-encoding", "gzip, deflate, sdch");
   Http.addheader ("Accept-language", "zh-cn,zh;q=0.8"); Http.addheader ("User-agent", "mozilla/5.0" (Windows NT 6.1;

   WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/46.0.2490.80 safari/537.36 "); http. Startrequest (New Inetresponselistener () {@Override public void onrequestcomplete (netresponse result) {if (re
      Sult.issuccess ()) {String resultstr = result.resultstr;
     RESULTSTR is the data returned by the network}else {Exception ee = result.getexception ();

  }
    }
   });
  catch (Exception e) {e.printstacktrace ();

 }
 }

The above is the calling end need to implement the source code, is not very few codes can complete the network request? Here is the veil of the network processing class.

2. Introduction to Main classes
1.AbstractRequester: An abstract network request class
2.MyHttpRequest:: An instantiated network request class. If developers have other special processing needs, they can inherit abstractrequester to implement Parseresponse
3.httpengine:httpclient network Engine class, the final network request is handled by this class
4.HttpRequestData: Parameter class passed to Asynctask
5.NetResponse: Response class returned to the caller
6.INetResponseListener: interface of asynchronous callbacks

The relationships between classes are shown in the following illustration:

2.1 Abstractrequester
Abstract Network Management class, class definition is as follows:

Public abstract class Abstractrequester extends Asynctask 
 

For some developers with other special needs, simply inherit the class and implement its abstract interface, and if it is a common requirement, you can use the following Myhttprequest class directly:

Abstract Httprequestdata createdata ();
Abstract Netresponse Parseresponse (InputStream in);

2.2 Myhttprequest
Inherits and implements the Abstractrequester network processing class, supports get and post types, and supports custom add headers parameters.
For ordinary network requests and returns are sufficient, developers can use them directly.

2.3 Httpengine
Network Request engine class. The main processes are as follows:
1. Create Createhttpclient
2. Determine the validity of parameters
3. Judge Get or Post
4. Create the corresponding httpget or HttpPost
5. Set various parameters
6. Call Httpclient.execute Execute network request
7. Analysis and judgement of network return results
8. Generate Stream object and return

2.4 Httprequestdata

A parameter class passed to the Asynctask to set various parameters for the HTTP request.

2.5 netresponse
The class object that is returned to the caller, including state, data, and exceptions.

2.6 Inetresponselistener
The definition is very simple, the source code is as follows:

Public interface Inetresponselistener {

 /**
  * Network request return
  * @param result/public
 void Onrequestcomplete (netresponse result);

}

As long as the caller implements this interface, the return result is received asynchronously, and the result is the Netresponse object.

-FAQ

1. Asynctask Note
we all know that Asynctask is asynchronous, so the network request is implemented through Asynctask, the advantage of Aynctask is lightweight asynchronous, and can manipulate UI thread, such as update progress bar. But Asynctask also has some of the following problems:
task needs to be created and enabled in the UI thread, so the creation and invocation of Abstractrequester objects Startrequest done in the UI thread
API 11 is 3.0, the asynctask is queued for execution, so if one of the tasks is more time-consuming, other network requests need to wait; If you want to execute synchronously, modify execute to Executeonexecutor (but not recommend this modification)

2. Permissions
to add network operation permissions in XML:

<uses-permission android:name= "Android.permission.INTERNET"/>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.