首页 > 解决方案 > 如何在 Java 中访问 HTTP 响应对象的值

问题描述

我正在向服务器发送请求并获得对 Response 对象的响应。它在邮递员中输出一个 Json 对象。我需要知道访问其中值的方法。这是我的代码。

public void onResponse(Call call, Response response) throws IOException {
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    }

    if(response.code() == 200) {
        //need to access the response object
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

这是邮递员针对同一请求的输出

[
    {
        "id": 1,
        "name": "a"
    },
    {
        "id": 2,
        "name": "Udana"
    },
]

当我这样尝试 JSONObject jsonObject = new JSONObject(response.toString());

它给出了以下错误

W/System.err:org.json.JSONException:java.lang.String 类型的值响应无法转换为 JSONObject

标签: javajsonhttphttpresponse

解决方案


您可以指定CallResponse键入。例如,代表 JSON 对象的 beanCall<List<IdNameType>>在哪里。IdNameType

以下草稿:

public void onResponse(Call<List<IdNameType>> call, Response<List<IdNameType>> response) throws IOException {
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    }

    if(response.code() == 200) {
            List<IdNameType> responseContent = response.body();
            // Use response
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

否则,您可以手动管理获取原始 OkHttp 响应的响应内容Response::raw


推荐阅读