A
A
Alexander F2019-01-25 11:16:39
Java
Alexander F, 2019-01-25 11:16:39

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

    }

Next I get a ResponseEntity and I don't know how to extract the given file with its name...
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 ?
            }

how to parse response ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander F, 2019-01-25
@Filex

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

If there are suggestions for improving the code, I will be glad to see them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question