有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java OkHttp获取失败的响应正文

我目前正在开发的应用程序的API使用JSON作为主要的数据通信方式,包括失败响应场景中的错误消息(响应代码!=2xx)

我正在迁移我的项目以使用Square的OkHttp网络库。但是我很难解析所说的错误消息。对于OkHttp的response.body().string(),显然只返回请求代码“解释”(Bad RequestForbidden,等等),而不是“真实的”正文内容(在我的例子中:描述错误的JSON)

如何获得真正的响应体?这在使用OkHttp时可能吗


举个例子,下面是我解析JSON响应的方法:

private JSONObject parseResponseOrThrow(Response response) throws IOException, ApiException {
        try {
            // In error scenarios, this would just be "Bad Request" 
            // rather than an actual JSON.
            String string = response.body().toString();

            JSONObject jsonObject = new JSONObject(response.body().toString());

            // If the response JSON has "error" in it, then this is an error message..
            if (jsonObject.has("error")) {
                String errorMessage = jsonObject.get("error_description").toString();
                throw new ApiException(errorMessage);

            // Else, this is a valid response object. Return it.
            } else {
                return jsonObject;
            }
        } catch (JSONException e) {
            throw new IOException("Error parsing JSON from response.");
        }
    }

共 (1) 个答案

  1. # 1 楼答案

    我觉得自己很笨。我现在知道为什么上面的代码不起作用了:

    // These..
    String string = response.body().toString();
    JSONObject jsonObject = new JSONObject(response.body().toString());
    
    // Should've been these..
    String string = response.body().string();
    JSONObject jsonObject = new JSONObject(response.body().string());
    

    TL;DR它应该是string()而不是toString()