0

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.

lin hiro
  • 3
  • 2

2 Answers2

0

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;
            }
    );
Elgayed
  • 1,129
  • 9
  • 16
0

In Java a String is not the same as a byte[] array. Therefore treating audio-content (which is binary data) as a string (i.e. text data) is begging for problems.
Instead, you should get the response body as byte[]. Then you can save the bytes to a file. For example like this:

ResponseEntity<byte[]> entity = restTemplate.getForEntity(url, byte[].class);
byte[] body = entity.getBody();
Path path = Paths.get("example.wav");
Files.write(path, body);
Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49