code: public InputStream fetch(HttpURLConnection connection, boolean readErrorStreamNoException) throws IOException {
          // create connection but before reading get the correct inputstream based on the compression and if error
          connection.connect();
  
          InputStream is;
          if (readErrorStreamNoException && connection.getResponseCode() >= 400 && connection.getErrorStream() != null)
              is = connection.getErrorStream();
          else
              is = connection.getInputStream();
  
          if (is == null)
              throw new IOException("Stream is null. Message:" + connection.getResponseMessage());
  
          // wrap
          try {
              String encoding = connection.getContentEncoding();
              if (encoding != null && encoding.equalsIgnoreCase("gzip"))
                  is = new GZIPInputStream(is);
              else if (encoding != null && encoding.equalsIgnoreCase("deflate"))
                  is = new InflaterInputStream(is, new Inflater(true));
          } catch (IOException ex) {
          }
  
          return is;
      }
docs: This method initiates a connect call of the provided connection and returns the response
  stream. It only returns the error stream if it is available and readErrorStreamNoException is
  true otherwise it throws an IOException if an error happens. Furthermore it wraps the stream
  to decompress it if the connection content encoding is specified.