我正在处理的应用程序的API使用JSON作为传递数据的主要方式 - 包括失败的响应方案中的错误消息(响应代码!= 2xx).
我正在迁移我的项目以使用Square的OkHttp网络库.但是我很难解析所说的错误信息.response.body().string()显然,对于OkHttp 来说,只返回请求代码"解释"(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.");
}
}
Run Code Online (Sandbox Code Playgroud)
我感到愚蠢.我现在知道为什么上面的代码不起作用:
// 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());
Run Code Online (Sandbox Code Playgroud)
TL; DR它应该是string()和不是 toString().
| 归档时间: |
|
| 查看次数: |
4641 次 |
| 最近记录: |