0

I've been searching through the web for a while now and wasn't able to find a proper solution, so i'm asking here.

I've got a Spring Application where I receive a POST request from the frontend (only knows the endpoint of the spring application). The controller should then do another POST request to another API which creates a PDF depending on the served data in the request and returns it. Now the question is: How can i do a Post Request and get the file which is being returned as attachment, so that Spring can send it back to my frontend (Angular).

So far i have the following:

@PostMapping(path = "/print/{username}")
    public File printCompetences(@PathVariable final String username,
                                 @RequestBody final List<PrintableCompetence> competences)
    {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String competencesJson = objectMapper.writeValueAsString(competences);

            URL url = new URL(flask_url);
            URLConnection con = url.openConnection();
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);
            try(OutputStream os = con.getOutputStream()) {
                byte[] input = competencesJson.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
        } catch (MalformedURLException malformedURLException) {
            System.err.println(malformedURLException.getMessage());
            malformedURLException.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

Would be nice if someone could help me with ideas on how to handle this :)

Andreas Rainer
  • 314
  • 4
  • 16

1 Answers1

0

if you're using spring, try using RestTemplate like this.

How to programmatically consume a file from a Rest API using Spring?

guchuan
  • 125
  • 1
  • 10