yangyang12138

导航

媒体文件下载

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);

 

posted on 2023-03-21 01:08  杨杨09265  阅读(40)  评论(0编辑  收藏  举报