Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc20ba3e

Browse files
committed
Improved image downaload
1 parent1d3dd99 commitc20ba3e

File tree

1 file changed

+31
-12
lines changed

1 file changed

+31
-12
lines changed

‎src/main/java/generateimages/ImageDownloader.java

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
importjava.net.http.HttpClient;
77
importjava.net.http.HttpRequest;
88
importjava.net.http.HttpResponse;
9+
importjava.net.http.HttpTimeoutException;
910
importjava.nio.file.Files;
1011
importjava.nio.file.Path;
1112
importjava.nio.file.Paths;
@@ -19,20 +20,38 @@ public static void downloadImage(String imageUrl, String destinationFile)
1920
// Create an HttpClient
2021
HttpClientclient =HttpClient.newHttpClient();
2122

22-
// Create an HttpRequest for the image URL with a timeout of 20 seconds
23-
HttpRequestrequest =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+
HttpRequestrequest =
25+
HttpRequest.newBuilder()
26+
.uri(URI.create(imageUrl))
27+
.timeout(Duration.ofSeconds(30))// Set timeout duration
28+
.build();
2729

28-
// Send the request and receive the response
29-
HttpResponse<InputStream>response =
30-
client.send(request,HttpResponse.BodyHandlers.ofInputStream());
30+
intattempts =0;
31+
intmaxRetries =2;
3132

32-
// Get the InputStream from the response and write it to a file
33-
Pathpath =Paths.get(destinationFile);
34-
try (InputStreaminputStream =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+
Pathpath =Paths.get(destinationFile);
41+
try (InputStreaminputStream =response.body()) {
42+
Files.copy(inputStream,path,StandardCopyOption.REPLACE_EXISTING);
43+
}
44+
// If successful, break out of the loop
45+
break;
46+
}catch (HttpTimeoutExceptionex) {
47+
attempts++;
48+
if (attempts >maxRetries) {
49+
thrownewIOException(
50+
"Failed to download image after " +attempts +" attempts: " +imageUrl,
51+
ex);
52+
}
53+
// Optionally, wait before retrying (e.g., Thread.sleep)
54+
}
3655
}
3756
}
3857
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp