Android cainiao Study Notes 25 ---- interaction with the server (2) Parse json data returned by the server and request server data using an open source component, 25 ---- json

Source: Internet
Author: User
Tags php server

Android cainiao Study Notes 25 ---- interaction with the server (2) Parse json data returned by the server and request server data using an open source component, 25 ---- json

Supplement: Possible PHP server problems:

If you use an apache server as the server program implemented by php, the configuration of the virtual host may affect debugging of android applications !!

The IP addresses accessed in android applications are 10.0.2.2. If multiple virtual hosts are configured in the apache virtual host configuration file, the requests to the first virtual host are parsed by default, when debugging android applications, place the virtual host configured by the corresponding server in the first virtual host in the configuration file. Otherwise, the requested file does not exist.

The server returns JSONData and in androidParse JSON in ApplicationData:

1. Create a json. php file and return data in json format.:

 1 <?php 2  3 if(isset($_REQUEST["username"])&& isset($_REQUEST["password"])){ 4  5       $username = $_REQUEST["username"]; 6  7       $password = $_REQUEST["password"]; 8  9       if($username == "zhangsan" && $password == "123"){10 11            $arr = array(12 13                       "errorCode"=>200,14 15                       "errorMsg"=>"login success"16 17            );18 19            echo json_encode($arr);20 21       }else{22 23            $arr = array(24 25                       "errorCode"=>404,26 27                       "errorMsg"=>"login failure"28 29            );30 31            echo json_encode($arr);32 33       }34 35 }else{36 37       $arr = array(38 39                       "errorCode"=>500,40 41                       "errorMsg"=>"illeagle params"42 43            );44 45       echo json_encode($arr);46 47 }48 49 ?>

The returned information is in the following format:

{"errorCode":500,"errorMsg":"illeagle params"}

 

A json object is represented in braces, and key-value pairs are stored internally. Keys and values are separated by colons, and multiple key-value pairs are separated by commas.

The format is as follows:

[{"errorCode":200,"errorMsg":"login success"},{"errorCode":200,"errorMsg":"login success"},{"errorCode":200,"errorMsg":"login success"}]

 

The brackets contain json objects separated by commas.

2. Classes required for parsing json data in Android include JSONObject and JSONArray.:

JSONObject directly uses the constructor of input string parameters to create a JSONObject instance, and then calls the corresponding get method to obtain the value of each key in json data.

When the returned data is strings in json format enclosed in brackets, JSONArray is required. You can also use string parameters to construct a JSONArray instance, then, you can obtain each JSONObject in the form of a subobject, and then use the JSONObject method to retrieve and parse the object separately.

Simple Example:

Add a Message Processing Method for Handler modification to MainActivity. Currently, data in json format is obtained through get or post. Therefore, add the parsing of json data:

 1 private Handler handler = new Handler(){ 2  3            public void handleMessage(android.os.Message msg) { 4  5                  if(msg.what == OK){ 6  7                       String str = msg.obj.toString(); 8  9                       try {10 11                             JSONObject obj = new JSONObject(str);12 13                             Log.i(TAG,obj.getString("errorCode"));14 15                             Log.i(TAG,obj.getString("errorMsg"));16 17                       } catch (JSONException e) {18 19                             // TODO Auto-generated catch block20 21                             e.printStackTrace();22 23                       }24 25                      26 27                  }28 29            }30 31 };

Running result:

 

 

Sometimes, the server may return some entity information. If the user logs on successfully, the server returns the information that stores the user's personal information for caching locally, you may want to directly resolve the returned JSON format data to an object class object to simplify the operation. The JSONObject class can also be used. You only need to obtain the values of each field and then construct object class objects through them. However, a simpler method is to use GSON.

3. parse json data using GSON:

There are two ways to use GSON in your project:

Method 1: Download The gson jar package from the Internet, put it in the libs directory of the project, and add it to the build path of the Project. Then you can directly use GSON.

Method 2: Download The GSON source code. You can download it on github, copy the source code to the src directory, and then use GSON directly.

The following is a simple example of GSON. For more information, see the GSON help document: the docs directory is included in the downloaded source code package, which is the help document used by GSON, for more information, see.

Create an object class to store the returned errorCode and errorMsg:

 1 package cn.csc.start.bean; 2  3   4  5 public class ResponseInfo { 6  7       private int errorCode; 8  9       private String errorMsg;10 11       public int getErrorCode() {12 13            return errorCode;14 15       }16 17       public void setErrorCode(int errorCode) {18 19            this.errorCode = errorCode;20 21       }22 23       public String getErrorMsg() {24 25            return errorMsg;26 27       }28 29       public void setErrorMsg(String errorMsg) {30 31            this.errorMsg = errorMsg;32 33       }34 35       public ResponseInfo(int errorCode, String errorMsg) {36 37            super();38 39            this.errorCode = errorCode;40 41            this.errorMsg = errorMsg;42 43       }44 45       public ResponseInfo() {46 47            super();48 49       }50 51 }

Modify the code for parsing json data in the message processing in Handler. This time, GSON is used for parsing:

1 Gson gson = new Gson();2 3 ResponseInfo info = gson.fromJson(str, ResponseInfo.class);4 5 Toast.makeText(MainActivity.this, info.getErrorCode()+info.getErrorMsg(), Toast.LENGTH_LONG).show();

Note that it is very easy to parse object class objects using GSON:

If you do not have special requirements, you can create a GSON instance by default. You can use GsonBuilder to create a GSON instance when special configurations are required. For details, refer to the instructions.

Call fromJson () to pass in the data to be parsed and the parsed object type to complete the resolution from the json format string to the object class object.

If it is a string in the form of json array, parsing is a little tricky:

For example, if you want to parse [{"errorCode": 200, "errorMsg": "login success" },{ "errorCode": 200, "errorMsg": "login success "}, {& quot; errorCode & quot;: 200, & quot; errorMsg & quot;: & quot; login success & quot;}] Is List <ResponseInfo>

However, you cannot List <ResponseInfo>. class. In this case, GSON provides a method to obtain generic type information:

UseTypeToken:

TypeToken< List<ResponseInfo>> list = new TypeToken< List<ResponseInfo>>() {};

 

Call list. getType () and pay attention to the returned Type object, while the fromJson () method of Gson has the second overload Type parameter.

Therefore, for [{"errorCode": 200, "errorMsg": "login success" },{ "errorCode": 200, "errorMsg": "login success "}, {"errorCode": 200, "errorMsg": "login success"}] The specific code for parsing is as follows:

1 Gson gson = new Gson();2 3 TypeToken<List<ResponseInfo>> list = new TypeToken<List<ResponseInfo>>(){};4 5 List<ResponseInfo> info_list = gson.fromJson(str, list.getType());

 

The preceding two methods are used to parse json data.

In addition to the built-in HttpURLConnection and HttpClient, you can also select some excellent open-source projects to simplify interaction with the server. For exampleAsyncHttpClient:

AsyncHttpClientYou can get it at github:

 

Search for async-http in github to find the project, and then clone or download the zip package to get the project.

In your project, The async-http method is like GSON. You can also directly use the source code or reference the jar package, depending on your preferences.

A simple example of async-http sending get and post requests:

Add two methods to MainActivity:

Use AsyncHttpClient to send a get request:

 1 private void async_get_test(){ 2  3            String username = et_username.getText().toString(); 4  5            String password = et_password.getText().toString(); 6  7            AsyncHttpClient client = new AsyncHttpClient(); 8  9            client.get("http://10.0.2.2/index.php?username="+username+"&password="+password, new AsyncHttpResponseHandler() {10 11                 12 13                  @Override14 15                  public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {16 17                       // TODO Auto-generated method stub18 19                       Message msg = new Message();20 21                       msg.what = OK;22 23                       msg.obj = new String(responseBody);24 25                       handler.sendMessage(msg);26 27                  }28 29                 30 31                  @Override32 33                  public void onFailure(int statusCode, Header[] headers,34 35                             byte[] responseBody, Throwable error) {36 37                       // TODO Auto-generated method stub38 39                       Message msg = new Message();40 41                       msg.what = OK;42 43                       msg.obj = new String(responseBody);44 45                       handler.sendMessage(msg);46 47                  }48 49            });50 51       }

Use AsyncHttpClient to send a post request:

 1 private void async_post_test(){ 2  3            String username = et_username.getText().toString(); 4  5            String password = et_password.getText().toString(); 6  7            AsyncHttpClient client = new AsyncHttpClient(); 8  9            RequestParams params = new RequestParams();10 11            params.add("username", username);12 13            params.add("password", password);14 15            client.post("http://10.0.2.2/index.php", params , new AsyncHttpResponseHandler() {16 17                 18 19                  @Override20 21                  public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {22 23                       // TODO Auto-generated method stub24 25                       Message msg = new Message();26 27                       msg.what = OK;28 29                       msg.obj = new String(responseBody);30 31                       handler.sendMessage(msg);32 33                  }34 35                 36 37                  @Override38 39                  public void onFailure(int statusCode, Header[] headers,40 41                             byte[] responseBody, Throwable error) {42 43                       // TODO Auto-generated method stub44 45                       Message msg = new Message();46 47                       msg.what = OK;48 49                       msg.obj = new String(responseBody);50 51                       handler.sendMessage(msg);52 53                  }54 55            });56 57 }

 

We can see that the AsyncHttpClient method is very simple:

Get method:

Create an AsyncHttpClient object and call the get method.

The only slightly complicated one is the second parameter of the get method: AsyncHttpResponseHandler. You need to create an anonymous internal class object and then override the two methods of AsyncHttpResponseHandler, they are the network request success callback method and network request failure callback method.

Post method:

There is only one more passing parameter than the get method:

RequestParams params = new RequestParams ();

Params. add ("username", username );

Params. add ("password", password );

Use the RequestParams object to store the parameters to be submitted and pass them to the post () method.

 

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.