java之通过Http下载文件

2,273 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

最近有个项目需要通过文件链接下载文件到本地 所以我写了个小demo去实现通过文件链接下载到本地文件夹里

主要运用到了 java的net包和io包

具体实现思路是 通过文件链接来new一个URL对象

URL url = new URL(urlStr);

然后再通过url对象去打开一个http连接去创建一个HttpURLConnection实例

 HttpURLConnection conn = (HttpURLConnection) url.openConnection();

然后可以对这个HttpURLConnection进行设置超时响应和设置链接响应参数等 然后得到一个文件的输入流

        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();

然后通过一个读取输入流的方法给转换成我们需要的文件字节数组 具体方法为创建一个为1024的字节数组 然后创建一个内存操作流对象做为缓冲区来对输入流去进行一个操作去把输入流给转化成字节数组

     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

然后再通过想要存储的文件路径去new一个文件目录出来 然后再创建一个FileOutputStream对象 去把得到的字节数组给写入到文件里 这样就完成了一个下载的过程。

具体详细代码如下 读者可自取

  public static String downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }

String fileinfo = file.getAbsolutePath();
        System.out.println(fileinfo + " download success");
        return fileinfo;

    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }