title: OkHttp - Get failed response body
body: <p>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).</p>
  
  <p>I'm migrating my project to use Square's <a href="https://github.com/square/okhttp" rel="noreferrer">OkHttp</a> networking library. But am having difficulties to parse said error messages. For OkHttp's <code>response.body().string()</code>, apparently, only returns request code "explanation" (<code>Bad Request</code>, <code>Forbidden</code>, etc) instead of the "real" body content (in my case: a JSON describing the error).</p>
  
  <p>How to get the real response body instead? Is this even possible when using OkHttp?</p>
  
  <hr>
  
  <p>As an illustration, here's my method for parsing JSON response:</p>
  
  <pre><code>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.");
          }
      }
  </code></pre>