zoukankan      html  css  js  c++  java
  • 使用java原生API模拟请求下载文件

     1     /**
     2      * 
     3      * @param urlPath
     4      *            下载路径
     5      * @param saveDir
     6      *            下载存放目录
     7      * @return 返回下载文件
     8      * @throws Exception
     9      */
    10     public static void downloadFile(String urlPath, String saveDir) throws Exception {
    11         URL url = new URL(urlPath);
    12         // 连接类的父类,抽象类
    13         URLConnection urlConnection = url.openConnection();
    14         // http的连接类
    15         HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
    16         // 设定请求的方法,默认是GET
    17         httpURLConnection.setRequestMethod("GET");
    18         // 设置字符编码
    19         httpURLConnection.setRequestProperty("Charset", "UTF-8");
    20         //状态码 200:成功连接
    21         int code = httpURLConnection.getResponseCode();    
    22         if (code == 200) {
    23             System.out.println("链接地址成功!");
    24         }
    25         InputStream inputStream = httpURLConnection.getInputStream();
    26         File file = new File(saveDir);
    27         OutputStream out = new FileOutputStream(file);
    28         int size = 0;
    29         byte[] buf = new byte[1024];
    30         while ((size = inputStream.read(buf)) != -1) {
    31             out.write(buf, 0, size);
    32         }
    33         inputStream.close();
    34         out.close();
    35     }
  • 相关阅读:
    nmap 查看内网存活主机
    msf ms17_010 port:445
    nmap 检测ms17-010 port:445
    msf mysql port:3306
    msf ssh port:22
    Wireshark的两种过滤器与BPF过滤规则
    Wireshark使用记录
    过滤搜索引擎的抓取数据
    WEB容器开启、关闭OPTIONS方法
    代码泄露到Github
  • 原文地址:https://www.cnblogs.com/lfyu/p/9560227.html
Copyright © 2011-2022 走看看