简体   繁体   English

OkHttp - 获取失败的响应正文

[英]OkHttp - Get failed response body

The API for an app I'm currently working on uses JSON as a main way of communicating data - including error messages in failed response scenario (response code != 2xx). 我正在处理的应用程序的API使用JSON作为传递数据的主要方式 - 包括失败的响应方案中的错误消息(响应代码!= 2xx)。

I'm migrating my project to use Square's OkHttp networking library. 我正在迁移我的项目以使用Square的OkHttp网络库。 But am having difficulties to parse said error messages. 但是我很难解析所说的错误信息。 For OkHttp's response.body().string() , apparently, only returns request code "explanation" ( Bad Request , Forbidden , etc) instead of the "real" body content (in my case: a JSON describing the error). 对于OkHttp的response.body().string() ,显然只返回请求代码“说明”( Bad RequestForbidden等)而不是“真实”正文内容(在我的情况下:描述错误的JSON)。

How to get the real response body instead? 如何获得真正的反应体? Is this even possible when using OkHttp? 使用OkHttp时甚至可以这样做吗?


As an illustration, here's my method for parsing JSON response: 作为一个例子,这是我解析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.");
        }
    }

I feel dumb. 我感到愚蠢。 I know now why above code won't work: 我现在知道为什么上面的代码不起作用:

// 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 It should've been string() and not toString() . TL; DR它应该是string()不是 toString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM