HttpClient获取并解析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;
    }
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: HttpClient可以通过HttpGet请求发送JSON数据,具体步骤如下: 1. 创建HttpClient对象 HttpClient httpClient = new DefaultHttpClient(); 2. 创建HttpGet对象 HttpGet httpGet = new HttpGet(url); 3. 设置请求头 httpGet.setHeader("Content-Type", "application/json"); 4. 发送请求并获取响应 HttpResponse response = httpClient.execute(httpGet); 5. 解析响应数据 String result = EntityUtils.toString(response.getEntity(), "UTF-8"); 以上就是使用HttpClient发送HttpGet请求发送JSON数据的步骤。需要注意的是,请求头中的Content-Type必须设置为application/json,否则服务器无法正确解析请求数据。 ### 回答2: HttpClientJava的一个HTTP客户端库,可用于发送HTTP请求并获取响应。使用HttpClient发送GET请求发送JSON数据,可以按照以下步骤进行: 1. 创建HttpClient实例 可以使用HttpClientBuilder类创建一个HttpClient实例。 ```java CloseableHttpClient httpClient = HttpClientBuilder.create().build(); ``` 2. 创建HttpGet实例 创建一个HttpGet实例,设置请求的URL和请求头(如果需要)。 ```java HttpGet httpGet = new HttpGet("http://example.com/api/data"); httpGet.addHeader("Content-Type", "application/json"); ``` 3. 发送请求 使用HttpClient实例调用execute方法发送请求,并获取HttpResponse实例。 ```java CloseableHttpResponse httpResponse = httpClient.execute(httpGet); ``` 4. 获取响应结果 从HttpResponse实例中获取请求的响应结果并处理。 ```java if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); StringBuilder responseBuilder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { responseBuilder.append(line); } String responseJsonString = responseBuilder.toString(); // 处理JSON响应数据 } ``` 以上就是发送GET请求发送JSON数据的步骤。在处理JSON响应数据时,可以使用Java内置的JSON库或第三方共享库如Google的Gson库来解析JSON数据,并将其转换为Java对象以方便使用。 ### 回答3: HttpClient是Apache下的一个HTTP请求的工具包,它可以简化HTTP客户端的编程工作,发送GET请求和POST请求很容易。 发送GET请求时,需要创建URI和HttpGet对象,然后利用HttpClient执行HttpGet请求。在发送请求时,可以设置参数,例如header和timeout等。HttpGet请求成功之后,可以利用HttpResponse对象来获取结果。 如果想发送Json类型的请求,需要构造一个特定的JSON数据对象。在HttpClient中,可以使用HttpEntity类和StringEntity类来封装请求数据HttpEntity是一个抽象类,而StringEntity是它的一个子类,它的构造函数接收一个Json字符串。 例如,可以按以下方式发送一个含有Json数据HttpGet请求: 1.首先创建一个Json对象,例如: JSONObject json = new JSONObject(); json.put("name", "Tom"); json.put("age", "18"); 2. 然后将该Json对象转换为String类型,例如: String sJson = json.toString(); 3. 最后,通过StringEntity将Json字符串封装成一个HttpEntity对象,例如: StringEntity stringEntity = new StringEntity(sJson); 4. 创建HttpGet对象,设置其URI和请求参数: HttpGet httpGet = new HttpGet("http://xxx.com/api/user"); httpGet.addHeader("Content-Type", "application/json"); 5. 发送HttpRequest请求: httpGet.setEntity(stringEntity); HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpGet); 6. 获取HttpResponse中的结果: HttpEntity httpEntity = httpResponse.getEntity(); String result = EntityUtils.toString(httpEntity); 当然,以上仅是一个简单的示例,如果需要处理更复杂的Json数据类型,可以使用JsonParser类进行解析。总之,在使用HttpClient发送Json数据请求时,需要注意请求的参数及请求头的设置,以及返回结果的处理方式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值