HttpClient獲取并解析JSON數據

jopen 11年前發布 | 256K 次閱讀 JSON JSON開發包

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;
}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!