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");
        }
    }
  • 相关阅读:
    c#中开发ActiveX的学习笔记
    [转]李战大师悟透delphi 第七章 组织你的模块
    在网页中实现QQ的屏幕截图功能
    vs.net的调试小技巧之#define debug(适合新手)
    socket中的byte消息格式设计
    [转]李战大师悟透delphi第五章 包
    [转]李战大师悟透delphi 第九章 多层体系结构
    [转]李战大师悟透delphi第一章 delphi的原子世界
    重温delphi之控制台程序:Hello World!
    silverlight中的socket编程注意事项
  • 原文地址:https://www.cnblogs.com/wendelhuang/p/7156899.html
Copyright © 2011-2022 走看看