比如说要读取对接系统的图片,但是要将图片保存在自己的服务器。

@Slf4j
public class ImageDownloaderUtil {
    public static void downloadImageToServer(String imageUrl, String serverPath) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // 设置超时和请求头
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0");

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = httpURLConnection.getInputStream()) {
                    // 使用 java.nio.file.StandardCopyOption.REPLACE_EXISTING 以替换已存在的文件
                    createParentDir(serverPath);

                    Path targetPath = Paths.get(serverPath);
                    Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
                    System.out.println("图片下载成功到服务器路径: " + targetPath);
            }
            } else {
                System.out.println("下载失败,HTTP 状态码: " + responseCode);
            }
            httpURLConnection.disconnect();
        } catch (IOException e) {
            System.out.println("下载时发生错误: " + e.getMessage());
        }
    }

    /**
     * 创建文件所在的父目录
     */
    public static void createParentDir(String filePath) {
        File file = new File(filePath);
        File parentDir = file.getParentFile();  // 获取父目录

        if (parentDir != null && !parentDir.exists()) {
            if (parentDir.mkdirs()) {
                System.out.println("创建目录成功: " + parentDir.getAbsolutePath());
            } else {
                System.out.println("创建目录失败: " + parentDir.getAbsolutePath());
            }
        }
    }
}
imageUrl:访问的图片地址
serverPath:最终保存的地址

使用实列,吧下面的俩个参数替换成自己的就可以了。

ImageDownloaderUtil.downloadImageToServer("https://pic/images/2025/1200343.jpg", "/room/web/image/20251101123.png");

更多推荐