HttpUtils { public static String buildHttpErrorMessage(final HttpURLConnection connection) throws IOException { final StringBuilder messageBuilder = new StringBuilder("(").append(connection.getResponseCode()).append(")"); if (connection.getResponseMessage() != null) { messageBuilder.append(" "); messageBuilder.append(connection.getResponseMessage()); } try (InputStreamReader isr = new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr)) { String output; messageBuilder.append("["); while ((output = br.readLine()) != null) { messageBuilder.append(output); } messageBuilder.append("]"); } finally { connection.disconnect(); } return messageBuilder.toString(); } private  HttpUtils(); static String buildHttpErrorMessage(final HttpURLConnection connection); static HttpURLConnection openPostConnection(final URL url); static HttpURLConnection openPostConnection(final URL url, final Map<String, String> headers); static HttpURLConnection openDeleteConnection(final URL url); static String readBody(final HttpURLConnection connection); static String encodeQueryParam(final String paramName, final String paramValue); static void closeConnection(final HttpURLConnection connection); static int getConnectTimeout(); static void setConnectTimeout(final int connectTimeout); static int getReadTimeout(); static void setReadTimeout(final int readTimeout);  }
@Test public void testBuildHttpErrorMessage() throws IOException { HttpURLConnection connectionMock = null ; String testResponseBody = "{\"error_description\":\"MSIS9612: The authorization code received in [code] parameter is invalid. \"}"; int testConnectionResponseCode =400; String testConnResponseMessage = "Bad Request."; try(InputStream in = new ByteArrayInputStream(testResponseBody.getBytes(StandardCharsets.UTF_8))) { connectionMock = Mockito.mock(HttpURLConnection.class); Mockito.when(connectionMock.getResponseCode()).thenReturn(testConnectionResponseCode); Mockito.when(connectionMock.getResponseMessage()).thenReturn(testConnResponseMessage); Mockito.when(connectionMock.getErrorStream()).thenReturn(in); String actual = HttpUtils.buildHttpErrorMessage(connectionMock); String expected = String.format("(%d) %s[%s]", testConnectionResponseCode, testConnResponseMessage, testResponseBody); Assert.assertTrue(expected.equals(actual)); } }