批量下载网页图片的工具类

 private static String getHtmlResourceByUrl(String url, String encoding) {

        //存储源代码的容器
        StringBuffer buffer=new StringBuffer();

        URL urlobj= null;
        URLConnection uc=null;
        InputStreamReader isr=null;
        BufferedReader reader=null;

        try {
            //建立网络连接
            urlobj=new URL(url);
            //打开网络连接
            uc=urlobj.openConnection();
            //防止屏蔽程序让我提示403
            //uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //建立文件写入流
            isr=new InputStreamReader(uc.getInputStream(),encoding);
            //建立文件缓冲流
            reader = new BufferedReader(isr);

            String temp=null;
            while((temp=reader.readLine()) != null){

                buffer.append(temp+"\n");//边读取一边写
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("你的网络不给力");
        }catch (IOException e) {
            e.printStackTrace();
            System.out.println("网络打开失败");
        }finally {
            if (isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return buffer.toString();
    }



    public static void download(String urlString, String filename,String savePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);

        // 打开连接
        URLConnection con = url.openConnection();
        //防止屏蔽程序让我提示403
        //con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //设置请求超时为5s
        con.setConnectTimeout(5000);
        // 输入流
        InputStream is = con.getInputStream();

        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File(savePath);
        if(!sf.exists()){
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
    }

 以上是获得网页整体框架和下载文件的方式,下面内容的代码就是下载图片或者查看源代码的方式,都只需少量修改即可,如需要下载视频也可以自己修改,只要协议和网址一样即可,这里我用到了Jsoup jar包

 public static void main(String[] args) {

        String url ="http://www.youku.com/";
        String encoding = "utf-8";
        //根据url网址和页面的编码集获取网页的源代码
        String html = getHtmlResourceByUrl(url,encoding);
        //System.out.println(html);
        //解析源代码
        Document document = Jsoup.parse(html);

        //获取所有图片地址
        Elements elements = document.getElementsByTag("img");
        for (Element element : elements) {
            String imgSrc = element.attr("src");
            //图片不为空且以//开头的文件
            if(!"".equals(imgSrc) && imgSrc.startsWith("//")){
                System.out.println("正在下载........");
                System.out.println("网络图片地址:"+imgSrc);
                String imgDown="http:"+imgSrc;

                try {
                    download(imgDown,imgSrc.substring(imgSrc.lastIndexOf("/"),imgSrc.length()),"G:\\迅雷下载\\实验\\");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

  

posted @ 2017-12-05 11:01  何晨昊  阅读(1057)  评论(0编辑  收藏  举报