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:
- Process asynchronous HTTP requests and handle callback results through anonymous internal classes
- HTTP requests are all in non-UI threads and do not block UI operations
- Process concurrent requests through the thread pool
- Process file upload and download
- Automatically package response results in JSON format
- Automatically reconnect requests when 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:
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"); } }
Use the URL specified by the GET request and the callback function to process the request results. 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 a JSON string as a parameter:
try {JSONObject jsonObject = 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(){@Overridepublic void onSuccess(JSONObject jsonObject) {super.onSuccess(jsonObject);}});} catch (JSONException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}
Officially recommended method of use, using a static request object, let's take a look at the official example of an API to access twitter:
Usage:
Because network requests are involved, do not forget to add permissions:
<uses-permission android:name="android.permission.INTERNET" />
Other functions, such as uploading and downloading files, can be viewed on the official website. I will not repeat them here!
To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group
At the same time, you are welcome to follow my Sina Weibo chat with me: @ Tang Ren _ Ryan