我目前正在开发的应用程序的API主要使用JSON通信数据,包括响应失败场景(响应代码!= 2xx)中的错误消息。
我正在将我的项目迁移到使用Square的OkHttp网络库。但是在解析上述错误消息时遇到了困难。对于OkHttp的response.body().string()
,显然仅返回请求代码“解释”(Bad Request
、Forbidden
等),而不是“真正”的正文内容(在我的情况下:描述错误的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.");
}
}
response.body().string()
两次时,第二次调用会导致程序抛出java.lang.IllegalStateException: closed
异常。 - 1111161171159459134