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");
        }
    }
  • 相关阅读:
    Delphi DataSnap入门操作,动起来
    Delphi 记录Record和字符串String相互赋值
    转载:JAVA每天学习
    转载:IntelliJ IDEA 的使用方法总结
    合并多个txt
    如何用vosviewer进行时间线分析——结合pajek
    链路预测(一)
    【js】百分比保留两位小数
    【基础】float保留两位小数
    【js】鼠标悬停显示信息
  • 原文地址:https://www.cnblogs.com/wendelhuang/p/7156899.html
Copyright © 2011-2022 走看看