android发送json并解析返回json

 
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 extends Activity {
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(new OnClickListener() {// 创建第一个单击事件
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 = new HttpGet(httpUrl);
49// 取得HttpClient对象
50HttpClient httpclient = new DefaultHttpClient();
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}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值