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).

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.");
        }
    }

Answer

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().

Leave a Reply

Your email address will not be published. Required fields are marked *