使用HttpURLConnection在AsyncTask中获取JSON数据时出错

时间:2015-09-08 22:01:18

标签: android json android-asynctask httpurlconnection

我试图从JSON获取URL数据时出现以下错误:

Value http of type java.lang.String cannot be converted to JSONObject

到目前为止,我使用了HttpClient,但是对于API23,它已被弃用,有人可以帮助我吗?

这就是我现在所拥有的:

@Override
protected String doInBackground(String... uri){

    String responseString = "...";

    URL url ;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(responseString);

        urlConnection = (HttpURLConnection) url
                .openConnection();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        assert urlConnection != null;
        urlConnection.disconnect();
    }

    return responseString;

}

这就是我所拥有的:

@Override
protected String doInBackGround(String...uri){
    String responseString = null;
    try {
        HttpClient client = new DefaultHttpClient();
        URI apiCall = new URI("...");
        HttpGet request = new HttpGet();
        request.setURI(apiCall);
        HttpResponse response = client.execute(request);
        responseString = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        Log.e("TAG", "some sort of problem encountered", e);
    }
    return responseString;
}

2 个答案:

答案 0 :(得分:0)

您可以执行GET

        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

要将json String转换为实际对象,可以使用Gson。  或者您可以忘记这个HttpURLConnection apprach并使用Retrofit库来实现相同的结果。

答案 1 :(得分:0)

您不会发布导致错误Value http of type java.lang.String cannot be converted to JSONObject的代码。但是,因为第一个代码段中的异步任务(使用HttpURLConnection)返回 responseString ,这是一个网址(例如以“http://”开头),当然,它是不是有效的JSONObject。