OkHttp - 获取失败的响应体

6

我目前正在开发的应用程序的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.");
        }
    }

3
实际上,在okhttp 2.4.0中,当您调用response.body().string()两次时,第二次调用会导致程序抛出java.lang.IllegalStateException: closed异常。 - 1111161171159459134
1个回答

7
我感觉很蠢。我现在知道为什么上面的代码不能工作了:
// 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());

简而言之 应该使用string(),而不是toString()


我知道..我知道.. -_- - Hadi Satrio
8
别感到愚蠢。Square应该为没有简单地覆盖toString()而感到愚蠢。 - Kevin Krumwiede
为什么不使用 peekBody() - IgorGanapolsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接