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).
I'm migrating my project to use Square's OkHttp networking library. 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).
How to get the real response body instead? Is this even possible when using OkHttp?
As an illustration, here's my method for parsing JSON response:
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.");
}
}
OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.
OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With