Http请求返回并解析json数据

  1. /*   注意get和post请求的发送区别 
  2.  * 1、创建HttpGet(或HttpPost)对象,将要请求的URL通过构造方法传入HttpGet(或HttpPost)对象中; 
  3.    2、使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST 请求,并返回HttpResponse对象; 
  4.    3、通过HttpResponse接口的getEntity方法返回响应信息。 
  5.  * */  
  6.   
  7. public class TestHttpActivity extends Activity {  
  8.   private Button btn_get;  
  9.   private Button btn_post;  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.         btn_get=(Button)findViewById(R.id.btn_get);  
  15.         btn_post=(Button)findViewById(R.id.btn_post);  
  16.         btn_get.setOnClickListener(listener);  
  17.         btn_post.setOnClickListener(listener);  
  18.     }  
  19.     private OnClickListener listener=new OnClickListener() {  
  20.           
  21.         @Override  
  22.         public void onClick(View v) {  
  23.             switch (v.getId()) {  
  24.             case R.id.btn_post:  
  25.                 Log.i("TestHttpActivity""ok");  
  26.                  DefaultHttpClient client = new DefaultHttpClient();   
  27.                  /**NameValuePair是传送给服务器的请求参数    param.get("name") **/  
  28.                  List<NameValuePair> list = new ArrayList<NameValuePair>();    
  29.                  NameValuePair pair1 = new BasicNameValuePair("name""name0001");    
  30.                  NameValuePair pair2 = new BasicNameValuePair("age""age0001");    
  31.                  list.add(pair1);    
  32.                  list.add(pair2);    
  33.                  UrlEncodedFormEntity entity=null;  
  34.                 try {  
  35.                     /**设置编码 **/  
  36.                     entity = new UrlEncodedFormEntity(list,"UTF-8");  
  37.                 } catch (UnsupportedEncodingException e) {  
  38.                     // TODO Auto-generated catch block  
  39.                     e.printStackTrace();  
  40.                 }    
  41.                 /**新建一个post请求**/  
  42.                  HttpPost post = new HttpPost("http://aaron-pc.wsd.com/Test/testHttp");    
  43.                  post.setEntity(entity);    
  44.                  HttpResponse response=null;  
  45.                  String strResult="";  
  46.                 try {  
  47.                     /**客服端向服务器发送请求**/  
  48.                     response = client.execute(post);  
  49.                 } catch (ClientProtocolException e) {  
  50.                     // TODO Auto-generated catch block  
  51.                     e.printStackTrace();  
  52.                 } catch (IOException e) {  
  53.                     // TODO Auto-generated catch block  
  54.                     e.printStackTrace();  
  55.                 }    
  56.                    /**请求发送成功,并得到响应**/  
  57.                  if(response.getStatusLine().getStatusCode()==200){    
  58.                     try {  
  59.                           /**读取服务器返回过来的json字符串数据**/  
  60.                            strResult = EntityUtils.toString(response.getEntity());     
  61.                     } catch (IllegalStateException e) {  
  62.                         // TODO Auto-generated catch block  
  63.                         e.printStackTrace();  
  64.                     } catch (IOException e) {  
  65.                         // TODO Auto-generated catch block  
  66.                         e.printStackTrace();  
  67.                     }  
  68.                       
  69.               
  70.                      JSONObject jsonObject = null;  
  71.                     try {  
  72.                         /**把json字符串转换成json对象**/  
  73.                         jsonObject = getJSON(strResult);  
  74.                     } catch (JSONException e1) {  
  75.                         // TODO Auto-generated catch block  
  76.                         e1.printStackTrace();  
  77.                     }  
  78.                      String names="";  
  79.                       
  80.                      try {  
  81.                          /** 
  82.                           * jsonObject.getString("code") 取出code 
  83.                           * 比如这里返回的json 字符串为 [code:0,msg:"ok",data:[list:{"name":1},{"name":2}]] 
  84.                           * **/  
  85.                            
  86.                          /**得到data这个key**/  
  87.                          String data=jsonObject.getString("data");  
  88.                          /**把data下的数据转换成json对象**/  
  89.                          JSONObject jDat = new JSONObject(data);  
  90.                          /**判断data对象下的list是否存在**/  
  91.                          if(jDat.get("list")!=null){  
  92.                              /**把list转换成jsonArray对象**/  
  93.                              JSONArray jarr = jDat.getJSONArray("list");  
  94.                              /**循环list对象**/  
  95.                          for (int i = 0; i < jarr.length(); i++) {  
  96.                                
  97.                              /** **/  
  98.                              JSONObject jsono = (JSONObject) jarr.get(i);   
  99.                                
  100.                              /**取出list下的name的值 **/  
  101.                              names=names+jsono.getString("name");  
  102.                                
  103.                         }  
  104.                          }  
  105.                         Toast.makeText(TestHttpActivity.this"code:"+jsonObject.getString("code")+"name:"+names, Toast.LENGTH_SHORT).show();  
  106.                     } catch (JSONException e) {  
  107.                         // TODO Auto-generated catch block  
  108.                         e.printStackTrace();  
  109.                     }    
  110.                          
  111.                          
  112.                  }    
  113.                  else Toast.makeText(TestHttpActivity.this"POST提交失败", Toast.LENGTH_SHORT).show();    
  114.                 break;  
  115.   
  116.             case R.id.btn_get:  
  117.                  DefaultHttpClient client1 = new DefaultHttpClient();   
  118.                  /**NameValuePair是传送给服务器的请求参数    param.get("name") **/  
  119.                  
  120.                  UrlEncodedFormEntity entity1=null;  
  121.                
  122.                 /**新建一个get请求**/  
  123.                  HttpGet get = new HttpGet("http://aaron-pc.wsd.com/Test/testHttp");    
  124.                  HttpResponse response1=null;  
  125.                  String strResult1="";  
  126.                 try {  
  127.                     /**客服端向服务器发送请求**/  
  128.                     response1 = client1.execute(get);  
  129.                 } catch (ClientProtocolException e) {  
  130.                     // TODO Auto-generated catch block  
  131.                     e.printStackTrace();  
  132.                 } catch (IOException e) {  
  133.                     // TODO Auto-generated catch block  
  134.                     e.printStackTrace();  
  135.                 }    
  136.                    /**请求发送成功,并得到响应**/  
  137.                  if(response1.getStatusLine().getStatusCode()==200){    
  138.                     try {  
  139.                           /**读取服务器返回过来的json字符串数据**/  
  140.                            strResult1 = EntityUtils.toString(response1.getEntity());     
  141.                     } catch (IllegalStateException e) {  
  142.                         // TODO Auto-generated catch block  
  143.                         e.printStackTrace();  
  144.                     } catch (IOException e) {  
  145.                         // TODO Auto-generated catch block  
  146.                         e.printStackTrace();  
  147.                     }  
  148.                       
  149.               
  150.                      JSONObject jsonObject1 = null;  
  151.                     try {  
  152.                         /**把json字符串转换成json对象**/  
  153.                         jsonObject1 = getJSON(strResult1);  
  154.                     } catch (JSONException e1) {  
  155.                         // TODO Auto-generated catch block  
  156.                         e1.printStackTrace();  
  157.                     }  
  158.                      String names="";  
  159.                       
  160.                      try {  
  161.                          /** 
  162.                           * jsonObject.getString("code") 取出code 
  163.                           * 比如这里返回的json 字符串为 [code:0,msg:"ok",data:[list:{"name":1},{"name":2}]] 
  164.                           * **/  
  165.                            
  166.                          /**得到data这个key**/  
  167.                          String data=jsonObject1.getString("data");  
  168.                          /**把data下的数据转换成json对象**/  
  169.                          JSONObject jDat1 = new JSONObject(data);  
  170.                          /**判断data对象下的list是否存在**/  
  171.                          if(jDat1.get("list")!=null){  
  172.                              /**把list转换成jsonArray对象**/  
  173.                              JSONArray jarr1 = jDat1.getJSONArray("list");  
  174.                              /**循环list对象**/  
  175.                          for (int i = 0; i < jarr1.length(); i++) {  
  176.                                
  177.                              /** **/  
  178.                              JSONObject jsono = (JSONObject) jarr1.get(i);   
  179.                                
  180.                              /**取出list下的name的值 **/  
  181.                              names=names+jsono.getString("name");  
  182.                                
  183.                         }  
  184.                          }  
  185.                         Toast.makeText(TestHttpActivity.this,  "get请求: code:"+jsonObject1.getString("code")+"name:"+names, Toast.LENGTH_SHORT).show();  
  186.                     } catch (JSONException e) {  
  187.                         // TODO Auto-generated catch block  
  188.                         e.printStackTrace();  
  189.                     }    
  190.                          
  191.                          
  192.                  }    
  193.                  else Toast.makeText(TestHttpActivity.this"get提交失败", Toast.LENGTH_SHORT).show();    
  194.                 break;  
  195.             }  
  196.               
  197.         }  
  198.     };  
  199.     public JSONObject getJSON(String sb) throws JSONException {    
  200.         return new JSONObject(sb);    
  201.     }   
  202.    

你可能感兴趣的:(httpclient,json)