Search code examples
javawavspring-resttemplate

springboot RestTemplate call url and https response headers(content-type:audio/wav) ,how to save as *.wav file?


I use spring RestTemplate to call the the Third-party services,

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

result like this:

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

response is enter image description here the body seems to wav data, I want to save the data to wav file.

if I Go directly to the link in chrome, it's ok to play, and download.


Solution

  • Use RestTemplate.execute instead, which allows you to attach a ResponseExtractor, in which you have access to the response body which an InputStream, we take that InputStream and write it to a file

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