简体   繁体   English

Spring - 对返回文件的 Rest Endpoint 执行 Post 请求

[英]Spring - Doing a Post Request to a Rest Endpoint which returns a file

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).我有一个 Spring 应用程序,我从前端接收一个 POST 请求(只知道 Spring 应用程序的端点)。 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.然后控制器应该向另一个 API 发出另一个 POST 请求,该请求根据请求中提供的数据创建 PDF 并返回它。 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).现在的问题是:我如何执行 Post 请求并获取作为附件返回的文件,以便 Spring 可以将其发送回我的前端(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 :)如果有人可以帮助我提供有关如何处理此问题的想法,那就太好了:)

if you're using spring, try using RestTemplate like this.如果您使用的是 spring,请尝试像这样使用RestTemplate

How to programmatically consume a file from a Rest API using Spring? 如何使用 Spring 以编程方式使用来自 Rest API 的文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM