0

我已经编写了两种几乎相同的方法来检索JSONObject. 较新的方法 throws ClientProtocolException,代码 500。我试图弄清楚这两种方法之间的区别可能会导致一种抛出异常,而另一种则可以正常工作。

方法#1:

public class MainActivity extends Activity
{
    // fluff

    protected JSONObject retrieveJSON()
    {
        HttpClient client = new DefaultHttpClient();
        String url = getString(R.string.url);
        String result = null;
        JSONObject json = null;

        try
        {
            HttpGet getMethod = new HttpGet(url);
            ReponseHandler<String> responseHandler = new BasicResponseHandler();
            result = client.execute(getMethod, responseHandler);

            json = new JSONObject(responseBody);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }   
}

方法#2

public class ServiceRequest
{
    public ServiceRequest()
    {
    }

    public ServiceRequest(String url)
    {
        this.URL = url;
    }

    public String URL;

    public String execute()
    {
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(this.URL);

        try
        {
            ResponseHandler<String> handler = new BasicResponseHandler();
            result = httpClient.execute(getRequest, handler);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return result;
    }
}

两种方法都返回result,然后将其处理为JSONObject. 或者至少,这两种方法都应该。我能想到的唯一主要区别是方法#1被编码为主要活动的类方法,而方法#2存在于独立类中。这种差异可能是引发的原因ClientProtocolException吗?

4

0 回答 0