public static byte [ ] retrieveRawData ( String sUrl , int timeout , SSLSocketFactory sslFactory ) throws IOException { URL url = new URL ( sUrl ) ; LOGGER . fine ( "Using the following URL for retrieving the data: " + url . toString ( ) ) ; HttpURLConnection conn = ( HttpURLConnection ) url . openConnection ( ) ; // set specified timeout if non-zero if ( timeout != 0 ) { conn . setConnectTimeout ( timeout ) ; conn . setReadTimeout ( timeout ) ; } try { conn . setDoOutput ( false ) ; conn . setDoInput ( true ) ; if ( conn instanceof HttpsURLConnection && sslFactory != null ) { ( ( HttpsURLConnection ) conn ) . setSSLSocketFactory ( sslFactory ) ; } conn . connect ( ) ; int code = conn . getResponseCode ( ) ; if ( code != HttpURLConnection . HTTP_OK && code != HttpURLConnection . HTTP_CREATED && code != HttpURLConnection . HTTP_ACCEPTED ) { String msg = "Error " + code + " returned while retrieving response for url '" + url + "' message from client: " + conn . getResponseMessage ( ) ; LOGGER . warning ( msg ) ; throw new IOException ( msg ) ; } try ( InputStream strm = conn . getInputStream ( ) ) { return IOUtils . toByteArray ( strm ) ; } // actually read the contents, even if we are not using it to simulate a full download of the data /*ByteArrayOutputStream memStream = new ByteArrayOutputStream(conn.getContentLength() == -1 ? 40000 : conn.getContentLength()); try { byte b[] = new byte[4096]; int len; while ((len = strm.read(b)) > 0) { memStream.write(b, 0, len); } } finally { memStream.close(); } if(LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Received data, size: " + memStream.size() + "(" + conn.getContentLength() + ") first bytes: " + replaceInvalidChar(memStream.toString().substring(0, Math.min(memStream.size(), REPORT_PEEK_COUNT)))); } return memStream.toByteArray();*/ } finally { conn . disconnect ( ) ; } }
Download data from an URL and return the raw bytes .