I am using RestTemplate to call a rest service which returns csv file which size is big. I used the below code. I am trying to store the response in a file.
import java.nio.file.Files; import java.nio.file.Path;
String fileName = "response.csv";
File file = new File(fileName);
Path filePath = file.toPath();
HttpEntity<Object> requestEntity = new HttpEntity<>(null, headers);
RestTemplate restTemplate = new RestTemplate();
InputStream responseStream = restTemplate
.exchange(serviceURL/LogFile"), HttpMethod.GET, requestEntity, InputStream.class).getBody();
try {
Files.copy(responseStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting this exception.
RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.io.InputStream] and content type [text/csv]
As per my understanding we need to write suitable message converters and add/register will rest template.
How to write suitable converter to get the csv response and store in a file?
you could download large file with below process:
RestTemplate restTemplate = new RestTemplate();
String FILE_URL = "serviceURL/LogFile";
File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
File ret = File.createTempFile("download", ".csv");
StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
return ret;
});
String fileName = "response.csv";
File destFile = new File(fileName);
FileUtils.copyFile(file, destFile);
for FileUtils you need to add "commons-io:commons-io:2.15.1" dependency