33.批量通过GET链接下载图片到指定文件夹下

通过JAVA循环调用照片下载链接

java 复制代码
package cn.com.goldwind.ercp.fems.controller.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * 批量下载附件
 * 图片名称为fileKey
 */
public class SimpleImageDownloader {
    // 配置超时时间(毫秒)
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 10000;

    public static void main(String[] args) {
        // 1. 定义要下载的图片URL列表
        List<String> imageUrls = Arrays.asList(
                  "https://baidu.com/fems/file/download/aad4803c8cb1479e98215cbc1def9d24"
                 ,"https://baidu.com/fems/file/download/2c25033166684effa09bb20ac71b38f5"
        );

        String saveDir = "E:/downloaded_images"; // 保存目录

        // 2. 循环执行下载
        for (int i = 0; i < imageUrls.size(); i++) {
            String urlStr = imageUrls.get(i);
            try {
                System.out.println("正在下载第 " + (i + 1) + "/" + imageUrls.size() + " 张: " + urlStr);
                downloadFile(urlStr, saveDir);
                System.out.println("成功: " + urlStr);
            } catch (Exception e) {
                System.err.println("失败: " + urlStr + " - 错误信息: " + e.getMessage());
            }
        }
        System.out.println("所有任务处理完毕。");
    }

    /**
     * 下载单个文件
     */
    public static void downloadFile(String fileUrl, String saveDir) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求属性
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        // 模拟浏览器User-Agent,防止被某些服务器拦截
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");

        // 检查响应码
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP错误码: " + responseCode);
        }

        // 获取输入流
        InputStream inputStream = connection.getInputStream();

        // 生成文件名:从URL最后部分截取,如果无法获取则用时间戳
        String fileName = getFileNameFromUrl(fileUrl);
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File outputFile = new File(dir, fileName);

        // 写入文件
        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
            byte[] buffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } finally {
            inputStream.close();
            connection.disconnect();
        }
    }

    /**
     * 从URL中提取文件名
     */
    private static String getFileNameFromUrl(String urlStr) {
        String[] parts = urlStr.split("/");
        String fileName = parts[parts.length - 1];
        // 如果文件名不包含扩展名或为空,给予默认名
//        if (fileName.isEmpty() || !fileName.contains(".")) {
//            fileName = "image_" + System.currentTimeMillis() + ".jpg";
//        }
        fileName += ".jpg";
        return fileName;
    }
}
相关推荐
Rain的Java大神之路5 分钟前
把 ThreadLocal 换成 ScopedValue 后,请求上下文为什么在子线程里"消失"了?三个边界 + 完整迁移指南(JDK 25)
java·后端·面试
inferno7 分钟前
Java正则表达式学习笔记
java·笔记·学习·正则表达式
会编程的吕洞宾1 小时前
JVM频繁Full GC排查实战_后端定位与调优
java·经验分享·后端
木井巳1 小时前
【动态规划: 子序列问题】最长递增子序列的个数
java·算法·leetcode·动态规划·推荐算法
nice_lcj5202 小时前
Spring 核心串讲:把 IoC、AOP、Boot、事务连成体系
java·spring boot·spring·面试·ioc·aop·体系串讲
nice_lcj5203 小时前
Spring Boot 入门:几行配置怎么跑起来
java·spring boot·spring·面试·自动配置·起步依赖
艾莉丝努力练剑3 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
Resean02233 小时前
SpringCloud 源码分析(二)Nacos 注册中心(上):服务注册流程与注册表模型
java·后端·spring·spring cloud
SimonKing4 小时前
别OCR了,都在用了OXR了,看那看那这款开源的OXR产品
java·后端·程序员
Rain的Java大神之路4 小时前
DTO、VO、PO 到底要不要拆?这场 Java 分层之争,今天一次讲透
java·后端·面试