首页 > 解决方案 > springboot RestTemplate 调用 url 和 https 响应头(内容类型:audio/wav),如何保存为 *.wav 文件?

问题描述

我使用spring RestTemplate 调用第三方服务,</p>

ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);

结果如下:

forEntity status:200 headers: content-type=audio/wav body:"RIFFä,,,xxxxxxx......"

响应是在此处输入图像描述 主体似乎是 wav 数据,我想将数据保存到 wav 文件。

如果我直接去chrome中的链接,就可以玩了,下载。

标签: javawavspring-resttemplate

解决方案


改为使用RestTemplate.execute,它允许您附加 a ResponseExtractor,您可以在其中访问response bodywhich an InputStream,我们将其InputStream写入文件

   restTemplate.execute(
            url, 
            HttpMethod.GET,
            request -> {}, 
            response -> {
                //get response body as inputstream
                InputStream in = response.getBody();
                //write inputstream to a local file
                Files.copy(in, Paths.get("C:/path/to/file.wav"), StandardCopyOption.REPLACE_EXISTING);
                return null;
            }
    );

推荐阅读