java - 从 HTTP 响应中获取 JSON 对象

标签 java android json

我想从 Http 获取响应中获取 JSON 对象:

这是我当前的 Http get 代码:

protected String doInBackground(String... params) {

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(params[0]);
    HttpResponse response;
    String result = null;
    try {
        response = client.execute(request);         
        HttpEntity entity = response.getEntity();

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            // now you have the string representation of the HTML request
            System.out.println("RESPONSE: " + result);
            instream.close();
            if (response.getStatusLine().getStatusCode() == 200) {
                netState.setLogginDone(true);
            }

        }
        // Headers
        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return result;
}

这里是 convertSteamToString 函数:

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

现在我只是得到一个字符串对象。如何取回 JSON 对象。

最佳答案

您得到的字符串只是 JSON Object.toString()。这意味着你得到了 JSON 对象,但是是 String 格式的。

如果你应该得到一个 JSON 对象,你可以放:

JSONObject myObject = new JSONObject(result);

关于java - 从 HTTP 响应中获取 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073849/

相关文章:

android - 需要在状态改变时关闭MediaRecorder播放的声音

android - 除了 Listview 之外,还有其他替代方法可以在 Android 中显示 MySQL 服务器数据吗?

android - 更快地启动不同进程中的 Activity

ios - 通过 JSON 作为字节数组发送图像数据

java - 为什么我们需要不可变的类?

javascript - 为什么 Unicode 组合字符顺序在 IDEA 和 Chrome 之间不同?

python - 如何在解析 Json 文件中的数据时仅获取 Python 脚本中所需的列

java - 如何将复杂的 JSON 结构从 Angular 发送到 Spring Controller

java - “直接 self 参照导致循环” jackson 和继承

java - 从更大的数组生成随机数数组?