JSON is a lightweight object that is small in size, easy to transmit, and easy to parse!
First, create a new class tool class Jsonutil to get the data returned by the request
Copy Code code as follows:
public class Jsonutil {
private static final String TAG = "Jsonutil";
public static Jsonobject Getjson (String url) throws Exception {
return new Jsonobject (getrequest (URL));
}
protected static string getrequest (string url) {
Return getrequest (URL, new defaulthttpclient (New Basichttpparams ()));
}
protected static string getrequest (string URL, defaulthttpclient client) {
String result = null;
int statusCode = 0;
HttpGet httpget = new HttpGet (URL);
try {
HttpResponse HttpResponse = Client.execute (HttpGet);
StatusCode = Httpresponse.getstatusline (). Getstatuscode ()///StatusCode 200 indicates that the request data was successful
result = Parseinputstream (httpresponse.getentity ());
catch (Clientprotocolexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
finally {
Httpget.abort ();
}
return result;
}
private static String Parseinputstream (httpentity entity) {
StringBuilder SB = null;
try {
SB = new StringBuilder ("");
InputStream InputStream = Entity.getcontent ();
int length = 0;
byte[] buffer = new byte[1024];
while (length = inputstream.read (buffer)) >-1) {
Sb.append (new String (buffer, 0, length));
}
return sb.tostring ();
catch (IllegalStateException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
return sb.tostring ();
}
}
To get the data and parse the data:
Note: The simulator can not use localhost:8080 or 127.0.0.1:8080 to access the Web site on its own computer, because the emulator defaults to the emulator itself as localhost, so if set to this way it will access the emulator itself. We need to modify the hostname to 10.0.2.2, which is the specific host name that the emulator sets up to access its own computer, and it records the name of your computer.
In addition: Getting the data requires that the following method be encapsulated into a new thread, not in the main program!
Copy Code code as follows:
/* http://10.0.2.2:8080/index.jsp
* {students:[{name: ' Livingstone ', age:25},{name: ' LS ', age:26}], class: ' 09GIS '}
*/
private void Livingstone () {
try {
String URL = "http://10.0.2.2:8080/index.jsp";
Gets the JSON object returned in the background--> {students:[{name: ' Livingstone ', age:25},{name: ' LS ', Age:26}],class: ' 09GIS class '}
Jsonobject jobj = Jsonutil.getjson (URL);
Get student array--> students:[{name: ' Livingstone ', age:25},{name: ' LS ', age:26}]
Jsonarray Jarr = Jobj.getjsonarray ("Students");
Get class--> class: ' 09GIS class '
String classname = jobj.getstring ("class");
Gets the JSON object--> {name: ' Livingstone ', age:25} for the first student based on the index
Jsonobject J1 = jarr.getjsonobject (0);
String studentinfo = jarr.length () + "student" + j1.getstring ("name")
+ J1.getint ("age");
catch (Exception e) {
E.printstacktrace ();
}
}