In the previous two blog "Android HTTP network programming (i)", "Android HTTP Network programming (ii)", the simple introduction of the Web page request and the client and the server side of the simple parameter interaction. Well, this blog will come to know the Android client gets the data returned by the server.
As you know, the general process for client-to-server interaction is as follows:
- The Android client makes a request to the server.
- The server receives the request and responds.
- The server returns data to the client.
For Android clients, the most important thing is to get the data returned by the server to show.
So, first we need to know what the data format is returned by the server? (Because of the data content returned by the server, we only need to complete the rendering.) So, more important is the format of the data, because different data formats get data in a slightly different way. The most common data formats are: JSON and XML two. (for the merits and demerits of these two data formats, please refer to the article "Comparison between JSON and XML") for the latter, there are three ways to parse XML: Pull parsing, sax parsing, Dom parsing. Personally think pull analysis is the simplest, please see another blog "Android XML parsing" (here only pull parsing, find time I put the other two also written)
In this blog, we focus on learning to return JSON-formatted data from the server side .
There are two types of data in JSON format, one is a JSON object and the other is an array of JSON objects.
Here we are to achieve:
We implement the get JSON object first.
We will copy the following JSON string into a new text file (that is, the one opened by Notepad), named "Testjson", and change the suffix to. json.
{"PubId": "001", "Pubtitle": "Testcontent", "Pubtime": "2014-9-30 12:01:13", "Pubauthor": "Admin"}
and put the file in the Tomcat file path (I put the path is e:\ programming software and Tools \tomcat\apache-tomcat-7.0.55\webapps\root\mytest), if you are not familiar with Tomcat, see the blog " Simple configuration and use of Tomcat in Android.
After placing the Tomcat file, launch the Tomcat service and enter the access address in the browser: Http://127.0.0.1:8080/mytest/testjson.json
The following results are obtained:
This is the data in the JSON format that we need to get through the browser.
Here we use code to implement:
(For convenience, access directly when the activity is started and output data return results)
Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); GetData (); } Private voidGetData () {NewThread (NewRunnable () {@Override Public voidrun () {HttpClient client=Newdefaulthttpclient (); HttpGet Get=NewHttpGet ("Http://192.168.1.101:8080/mytest/testjson.json"); HttpResponse response; Try{Response=Client.execute (GET); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {String str=entityutils.tostring (Response.getentity ()); //converts the returned string to a JSON objectJsonobject JSON =Newjsonobject (str); //gets the value corresponding to the label keyword of the JSON objectString id = json.getstring ("PubId"); String title= Json.getstring ("Pubtitle"); String author= Json.getstring ("Pubauthor"); String Time= Json.getstring ("Pubtime"); //output The value of a JSON objectSYSTEM.OUT.PRINTLN ("ID:" +ID); System.out.println ("Title:" +title); System.out.println ("Author:" +author); System.out.println ("Time:" +Time ); } } Catch(clientprotocolexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(jsonexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }}). Start (); }}
Note: You cannot access the network in the main thread after Android4.0, remember to add the network access permission in the manifest file: <uses-permission android:name= "Android.permission.INTERNET"/ >
Run the program with the following results:
In this way, we get the JSON-formatted data returned from the server side, which is not very simple.
Next we implement getting an array of JSON objects. This is similar to getting a JSON object above.
Replace the JSON object data source with an array of JSON objects, as follows:
[{"PubId": "001", "Pubtitle": "Test1", "Pubtime": "2014-9-30 12:01:13", "Pubauthor": "Admin"},{"PubId": "002", "Pubtitle" ":" Test2 "," Pubtime ":" 2014-9-31 12:01:13 "," Pubauthor ":" Admin "},{" PubId ":" 003 "," Pubtitle ":" Test3 "," Pubtime ":" 2014-9-31 "," Pubauthor ":" Admin "}]
The next action is the same as getting the JSON object.
We view in the browser:
Gets the code implementation for the JSON object array:
Private voidGetData () {NewThread (NewRunnable () {@Override Public voidrun () {HttpClient client=Newdefaulthttpclient (); HttpGet Get=NewHttpGet ("Http://192.168.1.101:8080/mytest/testjsonArray.json"); HttpResponse response; Try{Response=Client.execute (GET); if(Response.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {String str=entityutils.tostring (Response.getentity ()); //converts the returned string into an array of JSON objectsJsonarray Jsonarray =NewJsonarray (str); for(inti = 0; I < jsonarray.length (); i++) {
Gets a specific JSON object in the JSON array jsonobject JSON=Jsonarray.getjsonobject (i); //gets the value corresponding to the label keyword of the JSON objectString id = json.getstring ("PubId"); String title= Json.getstring ("Pubtitle"); String author= Json.getstring ("Pubauthor"); String Time= Json.getstring ("Pubtime"); //output The value of a JSON objectSYSTEM.OUT.PRINTLN ("ID:" +ID); System.out.println ("Title:" +title); System.out.println ("Author:" +author); System.out.println ("Time:" +Time ); System.out. println ("----------------Gorgeous split-line---------------------"); } } } Catch(clientprotocolexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(jsonexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }}). Start (); }
The results of the operation are as follows:
OK, now the usual operation to get JSON-formatted data is done.
In fact, if it is JSON, you can also use a third-party package to parse and obtain data, more convenient and fast. For example: Gson bag. Online usage is also more, interested in children's shoes can see.
Android HTTP network programming (III)