14.Android端请求服务器端的数据Ht…
原创
©著作权归作者所有:来自51CTO博客作者原小明呢的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.感受
服务器端的Servlet先将数据封装成JSON格式,通过IO中的PrintWriter,write出。
2.服务器端实现(Servlet)
List list;
//将list转成json格式(需要导入jar包)
JSONObject json=new JSONObject();
// 转成 jsonarray
JSONArray jsonArray=json.getJSONArray("list");
response.setContentType("text/plain");
PrintWriter pw=response.getWriter();
pw.write(jsonArray.toString());
pw.flush();
pw.close();
3.Android端
(1). 还是通过Httpclient来请求数据。(HttpResponse )
这里的 path是上面servlet地址。
public String getrubbishIfo(String path) {
//网络请求
StringBuilder sb = new StringBuilder();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = httpclient.execute(new HttpGet(path));
HttpEntity entity = httpResponse.getEntity(); if (entity != null) {
BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), "UTF- 8"), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
} } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return sb.toString();
}
(2)JSON解析
String body = client.getrubbishIfo(path);
//将数据转成JSONArray,通过循环得到对应的数据
JSONArray array = new JSONArray(body);
for (int i = array.length()-1; i >=0; i--) {
Map list = new HashMap();
JSONObject obj = array.getJSONObject(i);
(3)通过以上两部就可完成对数据的获取