14.Android端请求服务器端的数据Ht…

来源:互联网 发布:java 验证 数字 编辑:程序博客网 时间:2024/04/29 19:36

1.感受

      服务器端的Servlet先将数据封装成JSON格式,通过IO中的PrintWriter,write出。

 而到Android端的时候,通过访问该Servlet来得到数据,并进行JSON解析。

 

2.服务器端实现(Servlet) 

  例如:

         //得到服务器端的数据或者数据库里的数据存放在list中

        Listlist;    //user为用户对象,已有数据的list

 
        //将list转成json格式(需要导入jar包)
        JSONObject json=new JSONObject();
        json.put("list", list);

        // 转成 jsonarray
        JSONArray jsonArray=json.getJSONArray("list");
       response.setContentType("text/plain");
        PrintWriterpw=response.getWriter();
       pw.write(jsonArray.toString());
       pw.flush();
       pw.close();

   如果这步完成的话,将可以通过浏览器 ,来访问该servlet 来测试是否可以输出数据。

 

3.Android端

  (1).还是通过Httpclient来请求数据。(HttpResponse )

   示例:

   这里的 path是上面servlet地址。

   public StringgetrubbishIfo(String path) {
             //网络请求
              StringBuilder sb = new StringBuilder();
              HttpClient httpclient = newDefaultHttpClient();
              HttpResponse httpResponse;
            try {
              httpResponse= httpclient.execute(new HttpGet(path));
              HttpEntityentity = httpResponse.getEntity();

             if (entity !=null) {

     BufferedReaderreader = new BufferedReader( newInputStreamReader(entity.getContent(),"UTF-    8"), 8192);
    Stringline = null;
    while((line = reader.readLine()) != null) {
     sb.append(line+ "\n");
    }
    reader.close();
   }

  } catch(ClientProtocolException e) {
   // TODOAuto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODOAuto-generated catch block
   e.printStackTrace();
  }

  return sb.toString();
 }

  通过访问后,得到的是JSON格式字符串数据,下面将进行JSON解析,来得到数据:

 

(2)JSON解析

     //通过上面的到的JSON数据

    String body = client.getrubbishIfo(path);

     //将数据转成JSONArray,通过循环得到对应的数据
     JSONArrayarray = new JSONArray(body);
     for(int i = array.length()-1; i >=0; i--) {
      Maplist = new HashMap();
      JSONObjectobj = array.getJSONObject(i);

     //就可将数据存入list中

     list.put("name",obj.String(name));

     }

  (3)通过以上两部就可完成对数据的获取

 

 

 

 

 

 

 

0 0