Java Http Get方法下载图片代码

 //Java Http Get方法下载图片代码

public static boolean download(String uri, String path) throws IOException {
        URL url = new URL(uri);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setConnectTimeout(5000);
        conn.connect();
        //返回成功则存储图片
        if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
            String fileName = uri.substring(uri.lastIndexOf("/") + 1);
            File file = new File(path + "\\" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            InputStream input = conn.getInputStream();
//存储文件
            int len = 0;
            byte[] data = new byte[1024];
            while ((len = input.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
            fileOutputStream.close();
            input.close();
            return true;
        }
        //返回失败,则不存储直接返回
        return false;
    }
//调用代码
try {
   util.download("URL/XXXXXX.png", "电脑上存储路径");
} catch (Exception ex) {
    System.out.println(ex.toString());
}

 如果需要批量下载,循环调用即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Java中的Jsoup库和Java IO来下载汽车图片的示例代码: ```java import java.io.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.net.URL; public class DownloadCarImages { public static void main(String[] args) throws IOException { // 创建文件夹来保存图片 File dir = new File("./car_images"); if (!dir.exists()) { dir.mkdir(); } // 设置搜索关键词和下载图片的数量 String search_term = "car"; int num_images = 1000; // 构造搜索url String url = "https://www.google.com/search?q=" + search_term + "&tbm=isch"; // 发送get请求并解析响应内容 Document doc = Jsoup.connect(url).get(); // 提取所有图片标签 Elements imgTags = doc.getElementsByTag("img"); // 下载图片 int count = 0; for (Element imgTag : imgTags) { // 获取图片链接 String imgUrl = imgTag.attr("src"); try { // 发送get请求并以字节流形式保存图片 URL urlObj = new URL(imgUrl); InputStream in = urlObj.openStream(); OutputStream out = new BufferedOutputStream(new FileOutputStream("./car_images/" + count + ".jpg")); int i; while ((i = in.read()) != -1) { out.write(i); } in.close(); out.close(); count++; // 控制下载数量 if (count == num_images) { break; } } catch (IOException e) { continue; } } } } ``` 请注意,这只是一个示例代码,您需要根据实际情况进行修改,比如设置合适的搜索关键词和下载数量,以及处理异常情况等。同时,根据不同的网站和图片版权,下载图片可能涉及到法律问题,请您谨慎使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值