java使用 URLConnection完美实现图片的批量下载

闲来无事,自己使用 URLConnection封装了一个简陋的图片下载工具类,代码如下:

/**
     * 图片下载
     * @param imageUrl--要下载的图片url
     * @param formatName---存储时图片的名字
     * @param storePath--本地存储路径
     */
    public static void dowloaImage(String imageUrl, String formatName, String storePath) {
        InputStream is = null;
        FileOutputStream fos = null;
        File storeDir = new File(storePath);
        if(!storeDir.exists()){
            storeDir.mkdirs();
        }
        String[] str =imageUrl.substring(imageUrl.lastIndexOf("/")+1).split("\\.");
        String suffix =null;
        if(str.length==1){
            suffix="jpg";
        }else {
            suffix = str[1];
        }
        String filename = formatName+"."+suffix;

        try {
            URL url = new URL(imageUrl);
            URLConnection con = url.openConnection();
            is = con.getInputStream();
            fos = new FileOutputStream(new File(storeDir,filename));
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = is.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

测试如下:

 @org.testng.annotations.Test
    public void testLoadImage() {
        String url0 = "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2543938585,4255194900&fm=26&gp=0.jpg";
        String url1 = "http://wx3.sinaimg.cn/mw690/6adc108fly1fqlb309ittg20hi0bax6p.gif";
        String url2 = "http://img.soogif.com/CfzCz9rZkr1C33HE1HHa4W2ASRBZ9hPH.gif_s400x0";
        String[] urlArr = new String[]{url0, url1, url2};
        for (int i = 0; i < urlArr.length; i++) {
            ImageUtil.dowloaImage(urlArr[i], UUID.randomUUID().toString(), "/home/xiaoxin/图片/图片下载测试/");

        }
    }

结果:
在这里插入图片描述
可以看到,果真是实现了完美批量下载,哈哈哈,但bug总是无处不在.比如,csdn的png图片地址,如https://img-blog.csdnimg.cn/2020021321474014.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNjE1OTAz,size_16,color_FFFFFF,t_70
在这里插入图片描述
下载也下载了,也没报啥错,就是格式错误,为啥,因为在获取图片后缀名时如果没有类似.jpg形式的地址,我默认给了jpg,so 问题来了,万一这是一张png呢,那不就完了?存在格式问题了,可能导致文件无法正确打开.怎么解决呢这问题呢?URLConnection提供了一个方法可以获取响应内容的类型,

	URLConnection con = url.openConnection();
	String type =con.getContentType();
	System.out.println(type);

测试结果如下:
在这里插入图片描述
好啦,现在问题解决了.进一步修后如下:

/**
     * 图片下载
     * @param imageUrl--要下载的图片url
     * @param formatName---存储时图片的名字
     * @param storePath--本地存储路径
     */
    public static void dowloaImageGraceFully(String imageUrl, String formatName, String storePath) {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL(imageUrl);
            URLConnection con = url.openConnection();
            String type = con.getContentType();
            if (type.matches("image/.+")) {
                String filename =formatName+"."+type.substring(type.lastIndexOf("/")+1);
                File storeDir = new File(storePath);
                if (!storeDir.exists()) {
                    storeDir.mkdirs();
                }
                is = con.getInputStream();
                fos = new FileOutputStream(new File(storeDir, filename));
                byte[] buff = new byte[1024];
                int len = 0;
                while ((len = is.read(buff)) != -1) {
                    fos.write(buff, 0, len);
                }

            } else {
                System.out.println("不是图片类型,无法下载!" + imageUrl);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
@org.testng.annotations.Test
    public void testLoadImageGracefully() {
        String url0 = "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2543938585,4255194900&fm=26&gp=0.jpg";
        String url1 = "http://wx3.sinaimg.cn/mw690/6adc108fly1fqlb309ittg20hi0bax6p.gif";
        String url2 = "http://img.soogif.com/CfzCz9rZkr1C33HE1HHa4W2ASRBZ9hPH.gif_s400x0";
        String url3 = "https://www.csdn.net/";
        String url4 = "https://img-blog.csdnimg.cn/2020021321474014.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNjE1OTAz,size_16,color_FFFFFF,t_70";
        String[] urlArr = new String[]{url0, url1, url2,url3,url4};
        for (int i = 0; i < urlArr.length; i++) {
            ImageUtil.dowloaImageGraceFully(urlArr[i], UUID.randomUUID().toString(), "/home/xiaoxin/图片/图片下载测试2");

        }
    }

结果:
在这里插入图片描述

发布了17 篇原创文章 · 获赞 2 · 访问量 670

猜你喜欢

转载自blog.csdn.net/qq_43615903/article/details/104311303