zoukankan      html  css  js  c++  java
  • [JAVA]使用HttpURLConnection下载文件

    工程中用到一点通过HTTP读取文件的需求,一点样例代码。

    因为URL中不含有文件名,所以通过解析HTTP请求读取文件名。

    import java.io.File;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.RandomAccessFile;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
    import java.util.Map;
    import java.util.Set;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Test {
        public void download(String s) throws Exception {
            URL url = new URL(s);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            
            // 打印HTTP header
            Map headers = conn.getHeaderFields();
            Set<String> keys = headers.keySet();
            for(String key : keys) {
                System.out.println(key + " ----------------------------- " + conn.getHeaderField(key));
            }
            // 转换编码
            String contentDisposition = URLDecoder.decode(conn.getHeaderField("content-Disposition"), "UTF-8");
            System.out.println(contentDisposition);
            // 匹配文件名
            Pattern pattern = Pattern.compile(".*fileName=(.*)");
            Matcher matcher = pattern.matcher(contentDisposition);
            System.out.println(matcher.groupCount());
            System.out.println(matcher.matches());
            System.out.println(matcher.group(1));
            String filename = matcher.group(1);
            // 写盘
            RandomAccessFile file = new RandomAccessFile("D:/" + filename, "rw");
            InputStream stream = conn.getInputStream();
            byte buffer[] = new byte[1024];
            while (true) {
                int len = stream.read(buffer);
                if (len == -1) {
                    break;
                }
                file.write(buffer, 0, len);
            }
            if (file != null) {
                file.close();
            }
            if (stream != null) {
                stream.close();
            }
        }
    
        public static void main(String[] args) throws Exception{
            Test test = new Test();
            test.download("http://182.168.0.39:9099/fileupload/OA_FlowFJ_Download.do?tid=947810&tmp=1494918762208");
        }
    }
  • 相关阅读:
    java使用递归删除非空目录
    关于Java日期的两道例题
    equals和==的区别
    从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。
    输出所有的水仙花数
    99乘法表
    switch
    next()、nextInt()
    流程控制
    Scanner从键盘输入
  • 原文地址:https://www.cnblogs.com/wendelhuang/p/7156899.html
Copyright © 2011-2022 走看看