Java 模拟浏览器请求 获取资源 将网络图片下载到本地

publicclassDownLoadImageMBI {

 

   privatestatic String URL = "http://xxxxx.com/uploads/";

 

   publicstaticvoid main(String[] args) {

      try {

 

         readLineFile();

      }catch(Exception e) {

         e.printStackTrace();

      }

   }

 

   publicstaticvoid readLineFile() {

      List<String>list= newArrayList<>();

      try {

         FileInputStreamin = new FileInputStream("c:\\33.txt");

         InputStreamReaderinReader= newInputStreamReader(in,"UTF-8");

         BufferedReaderbufReader= newBufferedReader(inReader);

         Stringline= null;

 

         while ((line = bufReader.readLine()) != null) {

            list.add(line);

         }

         bufReader.close();

         inReader.close();

         in.close();

         for (String string : list) {

            String[]array= string.split(",");

            try {

                Stringencode= URLEncoder.encode(array[1], "UTF-8");

                download(URL + encode, array[0] + ".jpg", "f://mbi2");

            }catch(Exception e) {

                e.printStackTrace();

            }

 

         }

      }catch(Exception e) {

         e.printStackTrace();

      }

   }

 

   publicstaticsynchronizedvoid download(String urlString, String filename, String savePath) throws Exception {

     

      URLurl= newURL(urlString);

      // 打开连接

      HttpURLConnectioncon= (HttpURLConnection) url.openConnection();

      // 设置请求超时为5s

      con.setConnectTimeout(10 *1000);

      // 输入流

      InputStreamis = con.getInputStream();

 

      // 1K的数据缓冲

      byte[] bs = newbyte[1024];

      // 读取到的数据长度

      intlen;

      // 输出的文件流

      Filesf = new File(savePath);

      if (!sf.exists()) {

         sf.mkdirs();

      }

      OutputStreamos = new FileOutputStream(sf.getPath() + "\\" + filename);

      // 开始读取

      while ((len = is.read(bs)) != -1) {

         os.write(bs, 0, len);

      }

      // 完毕,关闭所有链接

      os.close();

      is.close();

   }

}

 

 

对于请求路径中含有中文的情况需要单独对中文经行编码

String encode = URLEncoder.encode(中文, "UTF-8");

一般的支持中文的编码UTF-8,GBK,GB2312,不同的浏览器用不同的编码根据以往经验谷歌UTF-8  百度GB2312 GBK

     欢迎大家关注我的微信公众号 您的关注就是我不懈的动力 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值