On the Android Network request library-android-async-http

Source: Internet
Author: User

There is a well-known ASIHttpRequest library in iOS development that is used to process network request operations. Today we will introduce an Android-async-http network request library that is equally powerful on android, currently, Instagram and Pinterest Android are very popular apps that use this network request library. This network request library 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. Its main features are as follows: It processes asynchronous Http requests and processes callback results through anonymous internal classes. All Http asynchronous requests are in non-UI threads and do not block UI operations, the thread pool processes concurrent requests to process file upload and download, and the response results are automatically packaged in JSON format. automatically process reconnection requests when the connection is disconnected. using android-async-http is also very simple, go to the official website to renew. Use the following code to create an asynchronous request: First, analyze the corresponding core operation class. AsyncHttpResponseHandler -- this is the class of BinaryHttpResponseHandler extends AsyncHttpResponseHandler, which inherits the subclass of AsyncHttpResponseHandler and is a byte stream return processing class, this class is used to process images. JsonHttpResponseHandler extends AsyncHttpResponseHandler -- inherits the subclass of AsyncHttpResponseHandler, which is a class used for json request return processing server and client communication. asyncHttpRequest implements Runnable -- a thread-based subclass used for asynchronous request classes and callback through AsyncHttpResponseHandler. PersistentCookieStore implements CookieStore -- this is a subclass Based on CookieStore. It uses HttpClient to process data and uses the cookie persistent storage interface. RequestParams -- encapsulates parameter processing, for example, copying Code * RequestParams params = new RequestParams (); * params. put ("username", "james"); * params. put ("password", "123456"); * params. put ("email", "my@email.com"); * params. put ("profile_picture", new File ("pic.jpg"); // Upload a File * params. put ("profile_picture2", someInputStream); // Upload an InputStream * params. put ("profile_picture3", new ByteArrayInputStream (someBytes )); // Upload some bytes ** AsyncHttpClient client = new AsyncHttpClient (); copy the code to the next core class. RetryHandler implements -- this is a SerializableCookie class that is synchronously processed by multiple threads; implements Serializable -- this is the SimpleMultipartEntity implements HttpEntity class for storing/retrieving data in operation cookies -- used to process multiple request entities encapsulate synchttpcli -- AsyncHttpClient for Synchronous client requests -- after the classes of asynchronous client requests introduce these core classes, let's take a look at its usage: this is the normal get method to return the code of the corresponding string: copy the code AsyncHttpClient client = new AsyncHttpClient (); client. get ("http://www.baidu.com", new AsyncHttpResponseHandler () {@ Override public void onSuccess (String response) {System. out. println (response); textView. setText (response) ;}@ Override public void onStart () {super. onStart (); System. out. println ("onStart") ;}@ Override public void onFinish () {super. onFinish (); System. out. println ("onFinish") ;}} at the same time, the request method also supports POST and PUT, and the request also supports parameter transmission. The following describes how to access the server using JSON strings as parameters: copy the code try {JSONObject json Object = new JSONObject (); jsonObject. put ("username", "ryantang"); StringEntity stringEntity = new StringEntity (jsonObject. toString (); client. post (MainActivity. this, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler () {@ Override public void onSuccess (JSONObject jsonObject) {super. onSuccess (jsonObject) ;}}) ;}catch (JSONException e) {e. printStackTrace ();} c Atch (UnsupportedEncodingException e) {e. printStackTrace ();} copies the Code. In addition, it also supports uploading corresponding file images. The source code is as follows: copy the code String path = "http://sv1.livechano.com: 8080/upload. action? & Action = 1.6 & type = 1 & ext = png "; File myFile = new File ("/sdcard/test.png "); RequestParams params = new RequestParams (); try {params. put ("image", myFile, "application/octet-stream"); AsyncHttpClient client = new AsyncHttpClient (); client. post (path, params, new AsyncHttpResponseHandler () {@ Override public void onFailure (Throwable error, String content) {// TODO Auto-generated method stub super. onFailur E (error, content); Toast. makeText (MainActivity. this, "Upload Failed! "+ Content, Toast. LENGTH_LONG ). show () ;}@ Override public void onSuccess (int statusCode, String content) {// TODO Auto-generated method stub super. onSuccess (statusCode, content); System. out. println ("content:" + content); Toast. makeText (MainActivity. this, "Upload successful! "+ Content, Toast. LENGTH_LONG ). show () ;}});} catch (FileNotFoundException e) {} copy the code. Note that params must be set for parameters uploaded using this method. put ("image", myFile, "application/octet-stream"); otherwise, it will fail. Of course, android-async-http still has many usage, so I will not repeat it too much here. We hope that android-async-http can help you with the android request module in the future.

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.