Answer the question
In order to leave comments, you need to log in
How to parse a ResponseEntity in java and get a file with a name?
You need to download the file from the server. The file is generated dynamically, depending on the passed parameters, its name changes. Here is the controller that gives the file:
@PostMapping(value = "/getFile")
public ResponseEntity<Resource> getNotFoundProviderGoods(@RequestParam("id") long id) throws IOException {
File file = new File(getFile(id));
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:7587/getFile");
httpPost.setHeader("X-CSRF-TOKEN", token);
httpPost.setHeader("Cookie", cookie);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addTextBody("providerId", String.valueOf(id)).setCharset(Charset.forName("UTF-8"))
.build();
httpPost.setEntity(reqEntity);
try (CloseableHttpResponse response = client.execute(httpPost)) {
System.out.println(response);
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
........... // как распарсить response ?
}
Answer the question
In order to leave comments, you need to log in
It turned out in the following way:
try (CloseableHttpResponse response = client.execute(httpPost)) {
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
String fileName = response
.getHeaders("Content-Disposition")[0]
.getElements()[0]
.getParameterByName("filename")
.getValue();
InputStream fis = response.getEntity().getContent();
Files.copy(fis, new File(fileName).toPath(), StandardCopyOption.REPLACE_EXISTING);
IOUtils.closeQuietly(fis);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question