6
6
import java .net .http .HttpClient ;
7
7
import java .net .http .HttpRequest ;
8
8
import java .net .http .HttpResponse ;
9
+ import java .net .http .HttpTimeoutException ;
9
10
import java .nio .file .Files ;
10
11
import java .nio .file .Path ;
11
12
import java .nio .file .Paths ;
@@ -19,20 +20,38 @@ public static void downloadImage(String imageUrl, String destinationFile)
19
20
// Create an HttpClient
20
21
HttpClient client =HttpClient .newHttpClient ();
21
22
22
- // Create an HttpRequest for the image URL with a timeout of 20 seconds
23
- HttpRequest request =HttpRequest .newBuilder ()
24
- .uri (URI .create (imageUrl ))
25
- .timeout (Duration .ofSeconds (20 ))// Set timeout duration
26
- .build ();
23
+ // Create an HttpRequest for the image URL with a timeout of 30 seconds
24
+ HttpRequest request =
25
+ HttpRequest .newBuilder ()
26
+ .uri (URI .create (imageUrl ))
27
+ .timeout (Duration .ofSeconds (30 ))// Set timeout duration
28
+ .build ();
27
29
28
- // Send the request and receive the response
29
- HttpResponse <InputStream >response =
30
- client .send (request ,HttpResponse .BodyHandlers .ofInputStream ());
30
+ int attempts =0 ;
31
+ int maxRetries =2 ;
31
32
32
- // Get the InputStream from the response and write it to a file
33
- Path path =Paths .get (destinationFile );
34
- try (InputStream inputStream =response .body ()) {
35
- Files .copy (inputStream ,path ,StandardCopyOption .REPLACE_EXISTING );
33
+ while (attempts <=maxRetries ) {
34
+ try {
35
+ // Send the request and receive the response
36
+ HttpResponse <InputStream >response =
37
+ client .send (request ,HttpResponse .BodyHandlers .ofInputStream ());
38
+
39
+ // Get the InputStream from the response and write it to a file
40
+ Path path =Paths .get (destinationFile );
41
+ try (InputStream inputStream =response .body ()) {
42
+ Files .copy (inputStream ,path ,StandardCopyOption .REPLACE_EXISTING );
43
+ }
44
+ // If successful, break out of the loop
45
+ break ;
46
+ }catch (HttpTimeoutException ex ) {
47
+ attempts ++;
48
+ if (attempts >maxRetries ) {
49
+ throw new IOException (
50
+ "Failed to download image after " +attempts +" attempts: " +imageUrl ,
51
+ ex );
52
+ }
53
+ // Optionally, wait before retrying (e.g., Thread.sleep)
54
+ }
36
55
}
37
56
}
38
57
}