OkHttp - get a rejected message

The API for the application I'm currently working on uses JSON as its primary mode of data transfer, including error messages in the bad response script (response code! = 2xx).

I am migrating my project to use the OkHttp networking library . But I am having difficulty parsing error messages. For OkHttp response.body().string()

, it seems to only return the request code "explain" ( Bad Request

, Forbidden

etc.) instead of the "real" body content (in my case: JSON describing the error).

How do I get the real body of the response? Is this possible when using OkHttp?


By way of illustration, here's my method to parse the 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.");
        }
    }

      

+3


source to share


1 answer


I feel stupid. Now I know why the code above doesn'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 He should string()

and didn't toString()

.

+5


source







All Articles