HttpClient获取并解析JSON数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package com.example.testjsonandget;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
 
import android.app.Activity;
import android.os.Bundle;
 
public class MainActivity  extends Activity {
     private final String uriString= "your url" ;
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         //服务器返回的JSON数据
         JSONObject jsonObject= this .getJSONObjectByGet();
         try {
             //从JSON中得到字符串
             String apiString=jsonObject.getString( "api" );
             String countString=jsonObject.getString( "count" );
             System.out.println( "apiString=" +apiString+ ",countString=" +countString);
             //从JSON中得到JSONArray,并且遍历
             JSONArray jsonArray=jsonObject.getJSONArray( "data" );
             for ( int i =  0 ; i < jsonArray.length(); i++) {
                 JSONObject everyJsonObject=jsonArray.getJSONObject(i);
                 String category_id=everyJsonObject.getString( "category_id" );
                 String category_name=everyJsonObject.getString( "category_name" );
                 String category_rgb=everyJsonObject.getString( "category_rgb" );
                 String category_news_count=everyJsonObject.getString( "category_news_count" );
                 System.out.println( "category_id=" +category_id+ ",category_name=" +category_name+
                 ",category_rgb=" +category_rgb+ ",category_news_count=" +category_news_count);
                 System.out.println( "=====================================================" );
             }
         catch (Exception e) {
             e.printStackTrace();
         }
     }
 
     //得到HttpClient
     public HttpClient getHttpClient(){
         HttpParams mHttpParams= new BasicHttpParams();
         //设置网络链接超时
         //即:Set the timeout in milliseconds until a connection is established.
         HttpConnectionParams.setConnectionTimeout(mHttpParams,  20 * 1000 );
         //设置socket响应超时
         //即:in milliseconds which is the timeout for waiting for data.
         HttpConnectionParams.setSoTimeout(mHttpParams,  20 * 1000 );
         //设置socket缓存大小
         HttpConnectionParams.setSocketBufferSize(mHttpParams,  8 * 1024 );
         //设置是否可以重定向
         HttpClientParams.setRedirecting(mHttpParams,  true );
         
         HttpClient httpClient= new DefaultHttpClient(mHttpParams);
         return httpClient;
     }
     
     //得到JSONObject(Get方式)
     public JSONObject getJSONObjectByGet(){
         JSONObject resultJsonObject= null ;
         if ( "" .equals(uriString)||uriString== null ) {
             return null ;
         }
         HttpClient httpClient= this .getHttpClient();
         StringBuilder urlStringBuilder= new StringBuilder(uriString);
         StringBuilder entityStringBuilder= new StringBuilder();
         //利用URL生成一个HttpGet请求
         HttpGet httpGet= new HttpGet(urlStringBuilder.toString());
         BufferedReader bufferedReader= null ;
         HttpResponse httpResponse= null ;
         try {
             //HttpClient发出一个HttpGet请求
             httpResponse=httpClient.execute(httpGet);      
         catch (Exception e) {
             e.printStackTrace();
         }
         //得到httpResponse的状态响应码
         int statusCode=httpResponse.getStatusLine().getStatusCode();
         if (statusCode==HttpStatus.SC_OK) {
             //得到httpResponse的实体数据
             HttpEntity httpEntity=httpResponse.getEntity();
             if (httpEntity!= null ) {
                 try {
                     bufferedReader= new BufferedReader
                     ( new InputStreamReader(httpEntity.getContent(),  "UTF-8" ),  8 * 1024 );
                     String line= null ;
                     while ((line=bufferedReader.readLine())!= null ) {
                         entityStringBuilder.append(line+ "/n" );
                     }
                     //利用从HttpEntity中得到的String生成JsonObject
                     resultJsonObject= new JSONObject(entityStringBuilder.toString());
                 catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         }
         return resultJsonObject;
     }
     
     //----------------------------------------以下为POST请求
     //准备进行POST请求的参数,一般而言将这些参数封装在HashMap中
     public JSONObject save(String title, String timelength)  throws Exception{
         Map<String,String> paramsHashMap =  new HashMap<String, String>();
         paramsHashMap.put( "title" , title);
         paramsHashMap.put( "timelength" , timelength);
         paramsHashMap.put( "method" "save" );
         String path =  "your url" ;
         return getJSONObjectByPost(path, paramsHashMap,  "UTF-8" );
     }
     //得到JSONObject(Post方式)
     //此方法此处未调用测试
     public JSONObject getJSONObjectByPost(String path,Map<String, String> paramsHashMap, String encoding) {
         JSONObject resultJsonObject =  null ;
         List<NameValuePair> nameValuePairArrayList =  new ArrayList<NameValuePair>();
         // 将传过来的参数填充到List<NameValuePair>中
         if (paramsHashMap !=  null && !paramsHashMap.isEmpty()) {
             for (Map.Entry<String, String> entry : paramsHashMap.entrySet()) {
                 nameValuePairArrayList.add( new BasicNameValuePair(entry.getKey(), entry.getValue()));
             }
         }
         
         UrlEncodedFormEntity entity =  null ;
         try {
             // 利用List<NameValuePair>生成Post请求的实体数据
             // 此处使用了UrlEncodedFormEntity!!!
             entity =  new UrlEncodedFormEntity(nameValuePairArrayList, encoding);
             HttpPost httpPost =  new HttpPost(path);
             // 为HttpPost设置实体数据
             httpPost.setEntity(entity);
             HttpClient httpClient =  this .getHttpClient();
             // HttpClient发出Post请求
             HttpResponse httpResponse = httpClient.execute(httpPost);
             if (httpResponse.getStatusLine().getStatusCode() ==  200 ) {
                 // 得到httpResponse的实体数据
                 HttpEntity httpEntity = httpResponse.getEntity();
                 if (httpEntity !=  null ) {
                     try {
                         BufferedReader bufferedReader =  new BufferedReader(
                         new InputStreamReader(httpEntity.getContent(), "UTF-8" ),  8 1024 );
                         StringBuilder entityStringBuilder =  new StringBuilder();
                         String line =  null ;
                         while ((line = bufferedReader.readLine()) !=  null ) {
                             entityStringBuilder.append(line +  "/n" );
                         }
                         // 利用从HttpEntity中得到的String生成JsonObject
                         resultJsonObject =  new JSONObject(entityStringBuilder.toString());
                     catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
             }
         catch (Exception e) {
             e.printStackTrace();
         }
         return resultJsonObject;
     }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值