注:模拟器访问自己电脑上的网站不能用localhost:8080或者127.0.0.1:8080,因为模拟器默认将模拟器本身设定为localhost,所以如果设置为这样的方式就将访问模拟器本身。我们需要将主机名修改为10.0.2.2,此主机名是模拟器设定的特定的访问自己电脑的主机名,它记录了你的电脑的名称。
/* 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";
// 获取后台返回的JSON对象 --> { students:[{name:'Livingstone',age:25},{name:'LS',age:26}],class:'09GIS班' }
JSONObject jObj = JsonUtil.getJSON(URL);
// 获取学生数组 --> students:[{name:'Livingstone',age:25},{name:'LS',age:26}]
JSONArray jArr = jObj.getJSONArray("students");
// 获取班级 --> class:'09GIS班'
String classname = jObj.getString("class");
// 根据索引获取第一个学生的JSON对象 --> {name:'Livingstone',age:25}
JSONObject j1 = jArr.getJSONObject(0);
String studentInfo = jArr.length() + "个学生" + j1.getString("name")
+ j1.getInt("age");
} catch (Exception e) {
e.printStackTrace();
}
}