zoukankan      html  css  js  c++  java
  • HttpClient实现通过url下载文件

    其实就是通过浏览器url,点击就会下载文件。

    这里是从代码层面上,对文件进行下载。

    package main.java.com.abp.util;
    
    import org.apache.http.*;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    
    public class HttpDownload {
        public static final int cache = 10 * 1024;
        public static final boolean isWindows;
        public static final String splash;
        public static final String root;
    
        static {
            if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
                isWindows = true;
                splash = "\";
                root = "D:";
            } else {
                isWindows = false;
                splash = "/";
                root = "/search";
            }
        }
    
        /**
         * 根据url下载文件,文件名从response header头中获取
         *
         * @param url
         * @return
         */
        public static String download(String url) {
            return download(url, null);
        }
    
        /**
         * 根据url下载文件,保存到filepath中
         *
         * @param url
         * @param filepath
         * @return
         */
        public static String download(String url, String filepath) {
            try {
                HttpClient client = HttpClients.createDefault();
                HttpGet httpget = new HttpGet(url);
                HttpResponse response = client.execute(httpget);
    
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                if (filepath == null){
                    filepath = getFilePath(response);
                }
    
                File file = new File(filepath);
                file.getParentFile().mkdirs();
                FileOutputStream fileout = new FileOutputStream(file);
                /**
                 * 根据实际运行效果 设置缓冲区大小
                 */
                byte[] buffer = new byte[cache];
                int ch = 0;
                while ((ch = is.read(buffer)) != -1) {
                    fileout.write(buffer, 0, ch);
                }
                is.close();
                fileout.flush();
                fileout.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 获取response要下载的文件的默认路径
         *
         * @param response
         * @return
         */
        public static String getFilePath(HttpResponse response) {
            String filepath = root + splash;
            String filename = getFileName(response);
    
            if (filename != null) {
                filepath += filename;
            } else {
                filepath += getRandomFileName();
            }
            return filepath;
        }
    
        /**
         * 获取response header中Content-Disposition中的filename值
         *
         * @param response
         * @return
         */
        public static String getFileName(HttpResponse response) {
            Header contentHeader = response.getFirstHeader("Content-Disposition");
            String filename = null;
            if (contentHeader != null) {
                HeaderElement[] values = contentHeader.getElements();
                if (values.length == 1) {
                    NameValuePair param = values[0].getParameterByName("filename");
                    if (param != null) {
                        try {
                            //filename = new String(param.getValue().toString().getBytes(), "utf-8");
                            //filename=URLDecoder.decode(param.getValue(),"utf-8");
                            filename = param.getValue();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return filename;
        }
    
        /**
         * 获取随机文件名
         *
         * @return
         */
        public static String getRandomFileName() {
            return String.valueOf(System.currentTimeMillis());
        }
    
        public static void outHeaders(HttpResponse response) {
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                System.out.println(headers[i]);
            }
        }
    
        public static void main(String[] args) {
            String url = "https://codeload.github.com/douban/douban-client/legacy.zip/master";
            String filepath = "F:\xxxx\workspace\httpClientProj\file\test.zip";
            HttpDownload.download(url, filepath);
        }
    }

    测试(可忽略,主要自己业务要用到)

    @Test
        public void test1(){
            String docRootPath =  "F:\xxxx\workspace\httpClientProj\file";
            String readFileName = "test.zip";
            String writeFileName = "write.zip";
    
            File readFile = new File(docRootPath+"\"+readFileName);
            File writeFile = new File(docRootPath+"\"+writeFileName);
    
            try {
                byte[] content1 = "CONTENT=".getBytes();
                byte[] content2 = FileUtils.readFileToByteArray(readFile);
    
                //拷贝文件文件
                FileUtils.writeByteArrayToFile(writeFile,content1);
                FileUtils.writeByteArrayToFile(writeFile,content2,true);
                System.out.println("------------------------------ok");
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Test
        public void test2(){
            String docRootPath =  "F:\xxxx\workspace\httpClientProj\file";
            String readFileName = "write.zip";
            String writeFileName = "write1.zip";
    
            File readFile = new File(docRootPath+"\"+readFileName);
            File writeFile = new File(docRootPath+"\"+writeFileName);
    
            try {
                byte[] content1 = "CONTENT=".getBytes();
                int startIndex = content1.length;
    
                byte[] content2 = FileUtils.readFileToByteArray(readFile);
    
                byte[] content3 = Arrays.copyOfRange(content2,startIndex,content2.length);
    
    
                //拷贝文件文件
                FileUtils.writeByteArrayToFile(writeFile,content3);
                System.out.println("------------------------------ok");
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
  • 相关阅读:
    JS事件冒泡、事件捕获和事件委托
    实现英文字母排序
    JavaScript异步加载的四种方法
    JavaScript作用域与作用域链
    JavaScript 自定义属性 data-*
    asycn和await
    style collectd
    JavaScript如何比较两个数组的内容是否相同
    VScode插件开发--M2D文档转换插件
    BOM笔记
  • 原文地址:https://www.cnblogs.com/xiaozhuanfeng/p/11186245.html
Copyright © 2011-2022 走看看