android解析json包(接口)

package com.http.test;
02   
03   
04 import org.apache.http.HttpResponse;
05 import org.apache.http.HttpStatus;
06 import org.apache.http.client.HttpClient;
07 import org.apache.http.client.methods.HttpGet;
08 import org.apache.http.impl.client.DefaultHttpClient;
09 import org.apache.http.util.EntityUtils;
10 import org.json.JSONException;
11 import org.json.JSONObject;
12 import org.json.JSONTokener;
13   
14   
15 import android.app.Activity;
16 import android.os.Bundle;
17 import android.view.View;
18 import android.view.View.OnClickListener;
19 import android.widget.Button;
20 //import android.widget.EditText;
21 import android.widget.TextView;
22   
23   
24 public class Http_testActivity extends Activity {
25 /** Called when the activity is first created. */
26 @Override
27 public void onCreate(Bundle savedInstanceState) {
28 super.onCreate(savedInstanceState);
29 setContentView(R.layout.main);
30   
31   
32 final TextView tv = (TextView) findViewById(R.id.result);
33 //final EditText ed = (EditText) findViewById(R.id.sendurl);
34 Button bt = (Button) findViewById(R.id.send);
35   
36   
37 bt.setOnClickListener(new OnClickListener() {// 创建第一个单击事件
38   
39   
40 public void onClick(View v) {
41   
42 String strResult = null;
43   
44   
45 try {
46 String httpUrl = "http://10.10.10.10:61002/userMessage/cJobConsultationUnread.json?data=688656&client_id=20012&view_id=268800";
47 // HttpGet连接对象
48 HttpGet httpRequest = new HttpGet(httpUrl);
49 // 取得HttpClient对象
50 HttpClient httpclient = new DefaultHttpClient();
51 // 请求HttpClient,取得HttpResponse
52 HttpResponse httpResponse = httpclient.execute(httpRequest);
53 // 请求成功
54 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
55 // 取得返回的字符串
56 strResult = EntityUtils.toString(httpResponse
57 .getEntity());
58 tv.setText(strResult);
59 } else {
60 tv.setText("请求错误!");
61 }
62   
63   
64 } catch (Exception e) {
65   
66   
67 }
68   
69 //返回的json串strResult={"status":0,"message":"OK","data":15}
70 try {  
71    
72    JSONTokener jsonParser = new JSONTokener(strResult);  
73    JSONObject js = (JSONObject) jsonParser.nextValue();  
74    // 接下来的就是JSON对象的操作了  
75    System.out.println("status的值是:"+js.getString("status"));  
76    System.out.println("message的值是:"+js.getString("message"));  
77    System.out.println("data的值是:"+js.getInt("data")); 
78      
79 } catch (JSONException ex) {  
80    // 异常处理代码  
81 }  
82   
83   
84 }
85   
86   
87 });
88   
89   
90 }
91 }

posted on 2013-07-26 15:58  jianrong.zheng  阅读(803)  评论(0编辑  收藏  举报

导航