【问题标题】:How to access the values of HTTP Response object in java如何在 Java 中访问 HTTP 响应对象的值
【发布时间】:2019-05-23 00:13:21
【问题描述】:

我正在向服务器发送请求并获得对 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

【问题讨论】:

  • 你能指定你正在使用的库吗?它看起来像改造。我说的对吗?
  • 是的,我正在尝试用 java 制作一个 android 应用

标签: java json http httpresponse


【解决方案1】:

您可以指定CallResponse 类型。例如,Call<List<IdNameType>>,其中IdNameType 是代表 JSON 对象的 bean。

草稿如下:

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();
        }
    }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多