Android HTTP客户端抛出异常

时间:2013-11-24 15:00:11

标签: java android heroku httpclient

我正在尝试构建一个以heroku服务器作为后端的Android应用程序。我试图通过heroku URL将JSON数据作为字符串。

这是json字符串的链接

  

http://le-wild-pesit.herokuapp.com/peeps/

并且网址的内容是

  

[{ “窥视”:{ “年龄”:NULL, “created_at”: “2013-11-23T08:58:09Z”, “ID”:1, “名” 的空值, “的updated_at”:“2013 -11-23T08:58:09Z “}},{” 窥视 “:{” 时代 “:空,” created_at “:” 2013-11-23T08:59:30Z”, “ID”:2, “名”:空 “的updated_at”: “2013-11-23T08:59:30Z”}}]

这是我的代码:

//imports go here
public class JSONParser 
{

public String getJSONFromUrl(String url)
{

    InputStream inpstr = null;
    String result = "";
    HttpResponse response = null;

    // HTTP
    try ,
    {           
        HttpClient httpclient = new DefaultHttpClient();
        try
        {
            response = httpclient.execute(new HttpGet(url));
            }
        catch(Exception e) 
        {
            return "dafuq?!";
        }
        HttpEntity entity = response.getEntity();
        inpstr = entity.getContent();
    } 
    catch(Exception e) 
    {
        return "SHIT!";
    }

    // Code to get string from input stream

 return result;

}

}

当我运行此代码时,我得到的回报是

  

“dafuq?!”

所以我假设我遇到了麻烦

  

response = httpclient.execute(new HttpGet(url));

我从2天开始修补代码,但我无法弄清楚出了什么问题。请帮帮我。

谢谢!

2 个答案:

答案 0 :(得分:2)

请确保您已向自己的应用程序授予INTERNET权限,请参阅this SO question有关如何执行该操作的权限。

另外,我建议您在代码中添加一些更具描述性的错误消息,例如查看e.getMessage()

答案 1 :(得分:1)

首先,网络操作应该异步完成,为此使用AsyncTask。其次,我建议使用Log函数进行错误处理。这里的工作代码( getJSON()是输入函数):

public void getJSON() {
    String[] strings = new String[]{"http://le-wild-pesit.herokuapp.com/peeps/"};
    new AsyncJSONTask().execute(strings);
}


public JSONArray getJSONFromUrl(String url) {
    String resultString;
    HttpResponse response;
    JSONArray jsonArray = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        response = httpclient.execute(new HttpGet(url));
        HttpEntity entity = response.getEntity();
        resultString = EntityUtils.toString(entity);
        jsonArray = new JSONArray(resultString);
    } catch (Exception e) {
        Log.e("SOME_TAG", Log.getStackTraceString(e));
    }
    return jsonArray;
}

private class AsyncJSONTask extends AsyncTask<String, Void, JSONArray> {

    @Override
    protected JSONArray doInBackground(String... params) {
        String url = params[0];
        return getJSONFromUrl(url);
    }

    @Override
    protected void onPostExecute(JSONArray jsonArray) {
        super.onPostExecute(jsonArray);
        //Here you do your work with JSON
    }
}