Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp - Get failed response body

Tags:

java

okhttp

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.");
        }
    }
like image 443
Hadi Satrio Avatar asked Jun 25 '15 02:06

Hadi Satrio


People also ask

Is OkHttp asynchronous?

OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.

What is OkHttp in Java?

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.


1 Answers

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

like image 59
Hadi Satrio Avatar answered Sep 28 '22 10:09

Hadi Satrio