您的位置:首页 > 移动开发 > Android开发

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

2015-08-02 12:59 344 查看
1.感受

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

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

 

2.服务器端实现(Servlet) 

  例如:

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

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

 

        
//将list转成json格式(需要导入jar包)

        
JSONObject json=new JSONObject();

        
json.put("list", list);

        // 转成 
jsonarray

        
JSONArray jsonArray=json.getJSONArray("list");

    
  
 response.setContentType("text/plain");

    
    PrintWriter
pw=response.getWriter();

    
  
 pw.write(jsonArray.toString());

    
  
 pw.flush();

    
  
 pw.close();

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

 

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();

 }

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

 

(2)JSON解析

     
//通过上面的到的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);

     
//就可将数据存入list中

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

     
}

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

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: