媒体文件下载

时间:2023-03-21
本文章向大家介绍媒体文件下载,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.普通方式

  直接用httpClient

public static void main(String[] args) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建HttpGet请求,相当于在浏览器输入地址
        HttpGet httpGet = new HttpGet("xxxx.mp3");


        File file = new File("/Users/yjw/work/data/xxx.mp3");
        file.createNewFile();

        FileOutputStream fileOutputStream = new FileOutputStream(file);

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {

                System.out.println(response.getEntity().getContentLength());

                response.getEntity().getContent();
                int b = response.getEntity().getContent().read();

                while (b > -1){
                    fileOutputStream.write(b);
                    System.out.println(b);
                    b = response.getEntity().getContent().read();
                }
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        } finally {
            if (response != null) {
                // 关闭资源
                response.close();
            }
            // 关闭浏览器
            httpclient.close();
        }
    }

2.因为媒体文件都是分片发送的采用flux更合适

DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory("http://xx/o.mp3");
        defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
        System.out.println(defaultUriBuilderFactory.builder().build().getRawQuery());
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/yjw/work/data/o.mp3");
        WebClient.builder().uriBuilderFactory(defaultUriBuilderFactory).build().
                get().
                retrieve().
                bodyToFlux(DataBuffer.class).
                subscribe(s->{

                    int b = 0;
                    while (b!=-1){
                        try {
                            b = s.asInputStream().read();
                            fileOutputStream.write(b);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    try {
                        fileOutputStream.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("===========");
                    System.out.println(s.readableByteCount());
        });

        Thread.sleep(12000);

原文地址:https://www.cnblogs.com/yangyang12138/p/17238559.html