Downloading multiple hosted image files

Imagine that you want to download multiple hosted images files without using an FTP client (or similar applications). Don't worry; you can do so by using the HTTP Client, either synchronously or asynchronously.

The code to do so is similar to what you saw in the preceding section; just save the response body bytes to a file with an appropriate file extension.

The following code downloads three hosted images from eJavaGuru (http://ejavaguru.com/) to the same folder as your source code file:

class MultipleImageDownload{ 
    public static void main(String args[]) throws Exception { 
        List<URI> imageURIs =  
List.of(  
URI.create("http://ejavaguru.com/images/about/jbcn-actual-2018.jpg"), 
URI.create("http://ejavaguru.com/images/about/iit-delhi.jpg"), 
URI.create("http://ejavaguru.com/images/about/techfluence.jpg")); 
 
        HttpClient client = HttpClient.newHttpClient(); 
 
        List<HttpRequest> imgDwnldRequests = imageURIs.stream() 
                                    .map(HttpRequest::newBuilder) 
                                    .map(builder -> builder.build()) 
                                    .collect(Collectors.toList()); 
 
        CompletableFuture.allOf(imgDwnldRequests.stream() 
            .map(request -> client.sendAsync(request, 
                                 BodyHandlers.ofFile( 
                                 Paths.get(((String)request.uri() 
                                        .getPath()).substring(14) 
                                     ) 
                                 ) 
                            )) 
                           .toArray(CompletableFuture<?>[]::new)) 
                           .join(); 
    } 
} 

The preceding code uses the same HttpClient instance, client, to download multiple hosted images, by sending multiple asynchronous requests to the server. The URI instance to the images is stored in a list of URIs: imageURIs. This list is then used to create multiple HttpRequest instances: imgDwnldRequests. Then, the code calls the sendAsync() method on the client, sending the requests asynchronously.

As stated in the previous example, BodyHandlers.ofFile() creates an implementation of BodyHandler, which creates and subscribes to BodySubscriber. BodySubscriber is a Reactive Stream subscriber that receives the response body from the server with non-blocking back pressure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.17.12