java下载远程url文件保存到本地 使用URL下载远程文件保存到本地

朱雀 2024-04-18 08:20 178阅读 0赞

java下载远程url文件保存到本地 使用URL下载远程文件保存到本地

#

一、需求说明

1、项目中使用到一个第三方插件,因插件经常更新,人工一次次的替换,很麻烦。于是乎有了需求,使用代码实现后台自动下载更新。

2、因是java的服务端项目,这里使用JDK提供的 java.net.* 包的,URLHttpURLConnection 实现文件下载。

二、代码如下

1、使用url 下载远程文件

  1. /**
  2. * description: 使用url 下载远程文件
  3. * @param urlPath --- url资源
  4. * @param targetDirectory --- 目标文件夹
  5. * @throws Exception
  6. * @return void
  7. * @version v1.0
  8. * @author w
  9. * @date 2019年9月3日 下午8:29:01
  10. */
  11. public static void download(String urlPath , String targetDirectory) throws Exception {
  12. // 解决url中可能有中文情况
  13. System.out.println("url:"+ urlPath);
  14. URL url = new URL(urlPath);
  15. HttpURLConnection http = (HttpURLConnection)url.openConnection();
  16. http.setConnectTimeout(3000);
  17. // 设置 User-Agent 避免被拦截
  18. http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
  19. String contentType = http.getContentType();
  20. System.out.println("contentType: "+ contentType);
  21. // 获取文件大小
  22. long length = http.getContentLengthLong();
  23. System.out.println("文件大小:"+(length / 1024)+"KB");
  24. // 获取文件名
  25. String fileName = getFileName(http , urlPath);
  26. InputStream inputStream = http.getInputStream();
  27. byte[] buff = new byte[1024*10];
  28. OutputStream out = new FileOutputStream(new File(targetDirectory,fileName));
  29. int len ;
  30. int count = 0; // 计数
  31. while((len = inputStream.read(buff)) != -1) {
  32. out.write(buff, 0, len);
  33. out.flush();
  34. ++count ;
  35. }
  36. System.out.println("count:"+ count);
  37. // 关闭资源
  38. out.close();
  39. inputStream.close();
  40. http.disconnect();
  41. }

2、获取文件名

  1. /**
  2. * description: 获取文件名
  3. * @param http
  4. * @param urlPath
  5. * @throws UnsupportedEncodingException
  6. * @return String
  7. * @version v1.0
  8. * @author w
  9. * @date 2019年9月3日 下午8:25:55
  10. */
  11. private static String getFileName(HttpURLConnection http , String urlPath) throws UnsupportedEncodingException {
  12. String headerField = http.getHeaderField("Content-Disposition");
  13. String fileName = null ;
  14. if(null != headerField) {
  15. String decode = URLDecoder.decode(headerField, "UTF-8");
  16. fileName = decode.split(";")[1].split("=")[1].replaceAll("\"", "");
  17. System.out.println("文件名是: "+ fileName);
  18. }
  19. if(null == fileName) {
  20. // 尝试从url中获取文件名
  21. String[] arr = urlPath.split("/");
  22. fileName = arr[arr.length - 1];
  23. System.out.println("url中获取文件名:"+ fileName);
  24. }
  25. return fileName;
  26. }

3、测试

  1. public static void main(String[] args) {
  2. Map<String,String> map = new HashMap<>();
  3. map.put("下载图片", "http://i1.zhiaigou.com/uploads/tu/201908/9999/152a0cd3b5.jpg");
  4. map.put("下载中文图片", "http://47.93.217.218/chapter/downloadServlet?fileName=%E4%B8%AD%E6%96%87%E5%9B%BE%E7%89%87.jpg");
  5. map.put("下载QQ软件", "https://qd.myapp.com/myapp/qqteam/pcqq/PCQQ2019.exe");
  6. map.put("下载带中文文件", "http://32204.xc.mieseng.com/xiaz/%E8%BF%85%E9%9B%B7%E5%A4%8D%E6%B4%BB%E7%89%88@68_416334.exe");
  7. map.put("该资源无法下载", "https://www.csc108.com/announcementNotice/showFile.json?id=685");
  8. try {
  9. for(String urlStr : map.values()) {
  10. download(urlStr, "E:/");
  11. }
  12. } catch (Exception e) {
  13. e.printStackTrace();
  14. }
  15. System.out.println("process over ...");
  16. }

4、效果如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0hhSGFfU2ly_size_16_color_FFFFFF_t_70

三、总结

1、这里只是用简单的使用 HttpURLConnection 实现从远程服务端获取文件下载,若有更高级需求,比如 爬虫,可以考虑使用 jsoup 来实现。

2、【二-2】中获取文件名,静态资源直接从url中获取,动态返回的文件流资源,需要从header中获取。 比如参考:https://blog.csdn.net/HaHa_Sir/article/details/79258556

3、若服务端设置了禁用java等方式访问,该代码可能无效,回抛出异常: Server returned HTTP response code: 521 for URL: xxx . 该示例代码中没有解决这个问题!

发表评论

表情:
评论列表 (有 0 条评论,178人围观)

还没有评论,来说两句吧...

相关阅读