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 ( final 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 ( ) ; }
Build error message from connection in case of failure