title: How to get response body using HttpURLConnection, when code other than 2xx is returned?
body: <p>I have problem with retrieving Json response in case when server returns error. See details below.</p>
  
  <h3>How I perform the request</h3>
  
  <p>I use <code>java.net.HttpURLConnection</code>. I setup request properties, then I do:</p>
  
  <pre><code>conn = (HttpURLConnection) url.openConnection();
  </code></pre>
  
  <p>After that, when request is successful, I get response Json:</p>
  
  <pre><code>br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
  sb = new StringBuilder();
  String output;
  while ((output = br.readLine()) != null) {
    sb.append(output);
  }
  return sb.toString();
  </code></pre>
  
  <h3>... and the problem is:</h3>
  
  <p>I can't retrieve Json received when the server returns some error like 50x or 40x,. Following line throws IOException:</p>
  
  <pre><code>br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
  // throws java.io.IOException: Server returned HTTP response code: 401 for URL: www.example.com
  </code></pre>
  
  <p>The server sends body for sure, I see it in external tool Burp Suite:</p>
  
  <pre><code>HTTP/1.1 401 Unauthorized
  
  {"type":"AuthApiException","message":"AuthApiException","errors":[{"field":"email","message":"Invalid username and/or password."}]}
  </code></pre>
  
  <p>I can get response message (i.e. "Internal Server Error") and code (i.e. "500") using following methods:</p>
  
  <pre><code>conn.getResponseMessage();
  conn.getResponseCode();
  </code></pre>
  
  <p>But I can't retrieve request body... maybe there is some method I didn't notice in the library?</p>