diff --git a/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java b/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java index d23c7b6b..bbf5111d 100644 --- a/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/GenerateServiceImpl.java @@ -3934,11 +3934,48 @@ public class GenerateServiceImpl extends ServiceImpl i } public byte[] downloadVideoOrImage(String url) { - try (CloseableHttpClient client = HttpClients.createDefault(); - InputStream in = client.execute(new HttpGet(url)).getEntity().getContent()) { - return IOUtils.toByteArray(in); - } catch (IOException e) { - throw new RuntimeException(e); + int maxRetries = 3; + int retryDelayMs = 1000; + IOException lastException = null; + + for (int attempt = 1; attempt <= maxRetries; attempt++) { + try { + return downloadWithTimeout(url, 30000, 60000); + } catch (IOException e) { + lastException = e; + log.warn("下载失败 (尝试 {}/{}): {}", attempt, maxRetries, e.getMessage()); + + if (attempt < maxRetries) { + try { + Thread.sleep((long) retryDelayMs * attempt); // 递增延迟 + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + throw new RuntimeException(ie); + } + } + } + } + + throw new RuntimeException("下载失败,已重试 " + maxRetries + " 次", lastException); + } + + private byte[] downloadWithTimeout(String url, int connectTimeout, int socketTimeout) throws IOException { + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(connectTimeout) + .setSocketTimeout(socketTimeout) + .setConnectionRequestTimeout(connectTimeout) + .build(); + + try (CloseableHttpClient client = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + CloseableHttpResponse response = client.execute(new HttpGet(url))) { + + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + throw new IOException("HTTP Error: " + statusCode); + } + return IOUtils.toByteArray(response.getEntity().getContent()); } }