[英]springboot RestTemplate call url and https response headers(content-type:audio/wav) ,how to save as *.wav file?
我使用 spring RestTemplate 調用第三方服務,
ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
結果如下:
forEntity status:200 headers: content-type=audio/wav body:"RIFFä,,,xxxxxxx......"
響應是在此處輸入圖像描述主體似乎是 wav 數據,我想將數據保存到 wav 文件。
如果我Go直接到chrome中的鏈接,就可以玩了,下載。
改用RestTemplate.execute
,它允許您附加一個ResponseExtractor
,您可以在其中訪問InputStream
的response body
,我們將該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;
}
);
在 Java 中, String
與byte[]
數組不同。 因此,將音頻內容(二進制數據)視為字符串(即文本數據)是有問題的。
相反,您應該將響應正文作為byte[]
。 然后您可以將字節保存到文件中。 例如像這樣:
ResponseEntity<byte[]> entity = restTemplate.getForEntity(url, byte[].class);
byte[] body = entity.getBody();
Path path = Paths.get("example.wav");
Files.write(path, body);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.