public static void download ( Logger log , URL downloadUrl , File target ) throws MojoExecutionException { log . progressStart ( ) ; try { OkHttpClient client = new OkHttpClient . Builder ( ) . readTimeout ( 30 , TimeUnit . MINUTES ) . build ( ) ; Request request = new Request . Builder ( ) . url ( downloadUrl ) . build ( ) ; Response response = client . newCall ( request ) . execute ( ) ; try ( OutputStream out = new FileOutputStream ( target ) ; InputStream im = response . body ( ) . byteStream ( ) ) { long length = response . body ( ) . contentLength ( ) ; InputStream in = response . body ( ) . byteStream ( ) ; byte [ ] buffer = new byte [ 8192 ] ; long readBytes = 0 ; while ( true ) { int len = in . read ( buffer ) ; readBytes += len ; log . progressUpdate ( target . getName ( ) , "Downloading" , getProgressBar ( readBytes , length ) ) ; if ( len <= 0 ) { out . flush ( ) ; break ; } out . write ( buffer , 0 , len ) ; } } } catch ( IOException e ) { throw new MojoExecutionException ( "Failed to download URL " + downloadUrl + " to " + target + ": " + e , e ) ; } finally { log . progressFinished ( ) ; } }
Download with showing the progress a given URL and store it in a file