Android Network request framework AsyncHttpClient instance details (with the JSON parsing call interface), asynchttpclientjson

Source: Internet
Author: User

Android Network request framework AsyncHttpClient instance details (with the JSON parsing call interface), asynchttpclientjson

Recently, the project requires the use of the network. I want to choose the AsyncHttpClient framework for APP development. Here we will summarize the problems I encountered during my work and the usage experience of AsyncHttpClient, hoping to help you with your learning.

First, follow the conventions to learn more about the AsyncHttpClient network framework.

1. Introduction

In Android, network requests generally use Apache HTTP Client or HttpURLConnect, but directly using these two class libraries requires a lot of code to complete the network post and get requests, the android-async-http library can greatly simplify operations. It is based on Apache's HttpClient and all requests are independent of the main UI thread. The request results are processed through callback, the android Handler message mechanism is used to transmit information.

2. Features

(1) Use asynchronous http requests and return results through anonymous internal classes

(2) http requests are independent of the main UI thread.

(3) Use a thread pool to process concurrent requests

(4) use the RequestParams class to create GET/POST Parameters

(5) Multipart file Upload is supported without a third-party package

(6) only 25 kb in size

(7) automatically reconnect requests when various mobile phones are disconnected

(8) ultra-fast support for automatic gzip response Decoding

(9) use the BinaryHttpResponseHandler class to download binary files (slices)

(10) The JsonHttpResponseHandler class can automatically parse the response results to the json format (The following describes the problems that JsonHttpResponseHandler has during use)

(11) Persistent cookie storage, which can be saved to SharedPreferences of your application

The above theory comes from the blog of netizens. If you are interested in learning more about AsyncHttpClient, refer to this blog.

Android Network request framework AsyncHttpClient details: http://blog.csdn.net/xiaohui2015/article/details/51462782

 

3. Usage

Before explaining an instance, read the interface documentation first, and learn more clearly by combining the interface documentation with the instance.

User Logon interface document:

Interface address: http://xxx.xxx.xxx/MobileService/userLogin

Note:

Request Parameters:

{

Username: "user logon ",

Password: "password"

}

Returned results:

{

"Code": "status code", 1000 returns success, other failures

"Message": "prompt message ",

"Data ":{

Userid: "User ID ",

Supplier: "supplier id ",

Suppliername: "Supplier name"

}

}

1 usercount = (EditText) findViewById(R.id.usernumber);2 password = (EditText) findViewById(R.id.password);

In the following code, usercount and password are two EditText controls defined on the interface. Used to enter the user's account and password.

1 AsyncHttpClient client = new AsyncHttpClient (); 2 String url = "http://xxx.xxx.xxx/MobileService/userLogin"; 3 // use RequestParams to send request parameters to the interface, the interface documentation shows that the parameters I want to send to the server are username and password 4 RequestParams params = new RequestParams (); 5 params. put ("username", usercount. getText (). toString (); 6 params. put ("password", password. getText (). toString (); 7 // note that here I use AsyncHttpResponseHandler for network processing, instead of Jso NHttpResponseHandler. The reason is described below. 8 // note that the post method must be used here, and do not forget to select the post with the params parameter when using client. Otherwise, what do you use to communicate with the server? I tried this mistake. 9 client. post (url, params, new AsyncHttpResponseHandler () {10 11 @ Override12 public void onSuccess (int arg0, Header [] arg1, byte [] arg2) {13 // TODO Auto-generated method stub14 try {15 // receives the returned data from the server and sets the character set. The returned result set is placed in resultDate, and resultDate is equivalent to a container, all returned information is included in the list. You only need to parse the returned values in JSON format and obtain the returned values one by one. 16 // I don't know why I use it. Only clear so easy to use. 17 String resultDate = new String (arg2, "UTF-8"); 18 // combined with the interface documentation, we can see that the returned results are all single, and no returned results are collections or arrays, therefore, directly use JSONObject to accept the return value. 19 JSONObject js = new JSONObject (resultDate); 20 // parse the code, message, and data. The return value is a single value instead of a set or array. 1: js. getJSONObject ("xxx"); 2: js. getString ("xxx"); xxx represents any String type String 21 // you can see from the interface documentation that the returned values are String type data, so I chose the second value method here. If the first method is used, it will cause Type mismatch and cause program errors. 22 String code = js. getString ("code"); 23 String message = js. getString ("message"); 24 String data = js. getString ("data"); 25 // further parses data. The principle is the same as above 26 JSONObject jsonObject = new JSONObject (data); 27 String userid = jsonObject. getString ("userid"); 28 String supplier = jsonObject. getString ("supplier"); 29 String suppliername = jsonObject. getString ("suppliername"); 30 // 1000 indicates the status code and 31 if ("1000 ". eq Uals (code) {32 // use SharedPreferences to store the user's account and password, for more information about SharedPreferences storage, see my other Article 33 SharedPreferences sharedPreferences = getSharedPreferences (34 message, Activity. MODE_PRIVATE); 35 Editor editor = sharedPreferences. edit (); 36 editor. putString ("username", usercount. getText () 37. toString (); 38 editor. putString ("password", password. getText () 39. toString (); 40 editor. commit (); 41 Intent intent = ne W Intent (getApplicationContext (), 42 MainActivity. class); 43 intent. putExtra ("userid", userid. toString (); 44 startActivity (intent); 45} else {46 Toast. makeText (getApplicationContext (), "incorrect account or password", 47 Toast. LENGTH_LONG ). show (); 48} 49} catch (UnsupportedEncodingException e) {50 // TODO Auto-generated catch block51 e. printStackTrace (); 52} catch (JSONException e) {53 // TODO Auto-generated catch block54 E. printStackTrace (); 55} 56 57} 58 59 @ Override60 public void onFailure (int arg0, Header [] arg1, byte [] arg2, 61 Throwable arg3) {62 // TODO Auto-generated method stub63 Toast. makeText (getApplicationContext (), "Check the network! ", 64 Toast. LENGTH_SHORT). show (); 65} 66}); 67

The above Code uses AsyncHttpResponseHandler () to process the return value of the server. AsyncHttpClient also has a return value for processing the server. I think most blogs write this JsonHttpResponseHandler ().

The code for JsonHttpResponseHandler () to process the server return value is as follows:

 

1 AsyncHttpClient client = new AsyncHttpClient (); 2 String url = "http://xxx.xxx.xxx/MobileService/userLogin"; 3 RequestParams params = new RequestParams (); 4 params. put ("username", usercount. getText (). toString (); 5 params. put ("password", password. getText (). toString (); 6 client. post (url, params, new JsonHttpResponseHandler () {7 @ Override 8 public void onSuccess (int statusCode, Header [] headers, 9 JSONObject response) {10 // TODO Auto-generated method stub11 super. onSuccess (statusCode, headers, response); 12 try {13 JSONObject js = new JSONObject (response. toString (); 14 String code = js. getString ("code"); 15 16 String message = js. getString ("message"); 17 String data = js. getString ("data"); 18 19 JSONObject jsonObject = new JSONObject (data); 20 String userid = jsonObject. getString ("userid"); 21 String supplier = jsonObject. getString ("supplier"); 22 String suppliername = jsonObject. getString ("suppliername"); 23 24 if ("1000 ". equals (code) {25 SharedPreferences sharedPreferences = getSharedPreferences (26 message, Activity. MODE_PRIVATE); 27 Editor editor = sharedPreferences. edit (); 28 editor. putString ("username", usercount. getText () 29. toString (); 30 editor. putString ("password", password. getTe Xt () 31. toString (); 32 editor. commit (); 33 Intent intent = new Intent (getApplicationContext (), 34 MainActivity. class); 35 intent. putExtra ("userid", userid. toString (); 36 startActivity (intent); 37} else {38 Toast. makeText (getApplicationContext (), "incorrect account or password", 39 Toast. LENGTH_LONG ). show (); 40} 41 42} catch (JSONException e) {43 // TODO Auto-generated catch block44 e. printStackTrace (); 45} 46} 47 48 @ Overri De49 public void onFailure (int statusCode, Header [] headers, 50 Throwable throwable, JSONArray errorResponse) {51 // TODO Auto-generated method stub52 super. onFailure (statusCode, headers, throwable, errorResponse); 53 Toast. makeText (getApplicationContext (), "Check the network! ", 54 Toast. LENGTH_SHORT). show (); 55} 56}); 57

 

For more information, see lines 6th and 9th. Line 6th uses JsonHttpResponseHandler () to process the returned data. The response parameter in the 9th line of code is the 10th in the above features: The JsonHttpResponseHandler class can automatically parse the response results into json format. Although JsonHttpResponseHandler () is very convenient, there are a lot of problems. During the use of JsonHttpResponseHandler (), sometimes the server cannot be requested inexplicably, that is, the onSuccess and onFailure methods cannot be used, which directly causes the program to become unavailable. If you don't believe it, you can try it. It's okay to use JsonHttpResponseHandler () to process the returned data a few minutes ago, and you haven't moved any code during this period, jsonHttpResponseHandler is inexplicably difficult to use, and the reason is unknown, no matter how you debug it, it is not successful. On the contrary, AsyncHttpResponseHandler () does not have such a problem. Therefore, I decided not to use JsonHttpResponseHandler (), but AsyncHttpResponseHandler () to process the returned data. Of course, AsyncHttpClient also encapsulates many other methods for processing the response, because others have not been used, and I do not know how to deal with them. If you have used other methods, you can leave a message below to tell me that we can learn from each other.

If the interface return value is in the form of an array or set, you can refer to the following code. I will not explain it. It is certainly no problem to write directly according to the code.

 

1 AsyncHttpClient client = new AsyncHttpClient (); 2 String url = "http://xxx.xxx.xxx/MobileService/userLogin"; 3 RequestParams params = new RequestParams (); 4 params. add ("userid", userid); 5 client. post (url, params, new AsyncHttpResponseHandler () {6 7 @ Override 8 public void onSuccess (int arg0, Header [] arg1, byte [] arg2) {9 // TODO Auto-generated method stub10 try {11 String resultDate = new Str Ing (arg2, "UTF-8"); 12 JSONObject js1 = new JSONObject (resultDate); 13 String code = js1.getString ("code "); 14 String message = js1.getString ("message"); 15 String data = js1.getString ("data"); 16 JSONObject js2 = new JSONObject (data); 17 if ("1000 ". equals (code) {18 String productlist = js2.getString ("productlist"); 19 JSONArray array = new JSONArray (productlist ); // The data returned by productlist is a collection of 20 // List <Map <St Ring, Object> arrays, which is declared in global variables. 21 arrays = new ArrayList <Map <String, Object> (); 22 for (int I = 0; I <array. length (); I ++) {23 JSONObject js3 = array. getJSONObject (I); 24 String batchnumber = js3.getString ("batchnumber"); 25 HashMap <String, Object> map = new HashMap <String, Object> (); 26 map. put ("batchnumber", batchnumber); 27 arrays. add (map); 28} 29 System. out. println ("arrays:" + arrays); 30 33} 34 35} catch (UnsupportedEncodingException e) {36 Log. e ("log_tag", 37 "Error parsing classname data" + e. toString (); 38} catch (JSONException e) {39 // TODO Auto-generated catch block40 Log. e ("log_tag", "Request failed" + e. toString (); 41} 42} 43 44 @ Override45 public void onFailure (int arg0, Header [] arg1, byte [] arg2, 46 Throwable arg3) {47 // TODO Auto-generated method stub48 Toast. makeText (getApplicationContext (), "service exception", 49 Toast. LENGTH_SHORT ). show (); 50} 51}); 52

I know so much about the use of the AsyncHttpClient network framework. I am grateful to anyone who knows what is going on. I hope this blog will help you.

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.