如何获得Web服务的JSONOBject?

时间:2014-11-19 13:43:51

标签: android json web-services androidhttpclient

我正在尝试获取Web服务的JSONObject。要做到这一点,我正在使用HttpClient与HttpResponse。当Web服务确实返回JSON时,我将更改返回到字符串并尝试创建一个JSONObject但仍然不起作用并返回null。

我该怎么做?

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;


public static JSONObject get(String url){       
        JSONObject jsonObj = null;

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(new HttpGet(url));
            HttpEntity entity = httpResponse.getEntity();
            if(entity != null){
                String s = EntityUtils.toString(entity);
                jsonObj = new JSONObject(s);                
            }           
        } catch (ClientProtocolException e) {           
            e.printStackTrace();
        } catch (IOException e) {           
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } 
        return jsonObj; 
    }

0 个答案:

没有答案
相关问题