android发送json并解析返回json

来源:互联网 发布:百度人工智能智库 编辑:程序博客网 时间:2024/05/19 23:29
 
01package com.http.test;
02  
03  
04import org.apache.http.HttpResponse;
05import org.apache.http.HttpStatus;
06import org.apache.http.client.HttpClient;
07import org.apache.http.client.methods.HttpGet;
08import org.apache.http.impl.client.DefaultHttpClient;
09import org.apache.http.util.EntityUtils;
10import org.json.JSONException;
11import org.json.JSONObject;
12import org.json.JSONTokener;
13  
14  
15import android.app.Activity;
16import android.os.Bundle;
17import android.view.View;
18import android.view.View.OnClickListener;
19import android.widget.Button;
20//import android.widget.EditText;
21import android.widget.TextView;
22  
23  
24public class Http_testActivity extendsActivity {
25/** Called when the activity is first created. */
26@Override
27public void onCreate(Bundle savedInstanceState) {
28super.onCreate(savedInstanceState);
29setContentView(R.layout.main);
30  
31  
32final TextView tv = (TextView) findViewById(R.id.result);
33//final EditText ed = (EditText) findViewById(R.id.sendurl);
34Button bt = (Button) findViewById(R.id.send);
35  
36  
37bt.setOnClickListener(newOnClickListener() {// 创建第一个单击事件
38  
39  
40public void onClick(View v) {
41  
42String strResult = null;
43  
44  
45try {
46String httpUrl = "http://10.10.10.10:61002/userMessage/cJobConsultationUnread.json?data=688656&client_id=20012&view_id=268800";
47// HttpGet连接对象
48HttpGet httpRequest = newHttpGet(httpUrl);
49// 取得HttpClient对象
50HttpClient httpclient = newDefaultHttpClient();
51// 请求HttpClient,取得HttpResponse
52HttpResponse httpResponse = httpclient.execute(httpRequest);
53// 请求成功
54if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
55// 取得返回的字符串
56strResult = EntityUtils.toString(httpResponse
57.getEntity());
58tv.setText(strResult);
59} else{
60tv.setText("请求错误!");
61}
62  
63  
64} catch(Exception e) {
65  
66  
67}
68  
69//返回的json串strResult={"status":0,"message":"OK","data":15}
70try {  
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}

原创粉丝点击