[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");
    }
}

 

posted @ 2017-07-12 18:21  weiwei5987  阅读(6577)  评论(0编辑  收藏  举报