HttpURLConnection从链接下载数据存放本地临时文件,Java

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection从链接下载数据存放本地临时文件,Java相关的知识,希望对你有一定的参考价值。

HttpURLConnection从链接下载数据存放本地临时文件,Java

    private File download(String url) throws Exception 
        HttpURLConnection connection = getConnection(url);

        int contentLength = connection.getContentLength();

        String msg = connection.getResponseMessage();
        System.out.println(msg);

        InputStream is = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        File tempFile = File.createTempFile(UUID.randomUUID().toString(), "");
        FileOutputStream fos = new FileOutputStream(tempFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int c;
        int count = 0;
        byte[] buf = new byte[1024 * 4];
        double pcent;
        while (true) 
            c = bis.read(buf);
            if (c == -1)
                break;
            bos.write(buf, 0, c);

            count = count + c;

            pcent = (count / (double) contentLength) * 100;
            System.out.print("已下载:" + String.format("%.2f", pcent) + "% \\r");
        

        bis.close();
        bos.close();
        fos.close();

        return tempFile;
    

    private HttpURLConnection getConnection(String u) throws Exception 
        URL url = new URL(u);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.connect();

        return connection;
    

以上是关于HttpURLConnection从链接下载数据存放本地临时文件,Java的主要内容,如果未能解决你的问题,请参考以下文章

把-图片的链接-下载到本地(服务器);

HttpURLConnection 传输数据和下载图片

JAVA通过HttpURLConnection 上传和下载文件

Android-HttpURLConnection获取下载文件大小

如何从 HttpURLConnection 读取 json 数据

HttpsURLConnection HttpURLConnection下载图片