繁体   English   中英

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

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

我已经在网上搜索了一段时间,但无法找到合适的解决方案,所以我在这里问。

我有一个 Spring 应用程序,我从前端接收一个 POST 请求(只知道 Spring 应用程序的端点)。 然后控制器应该向另一个 API 发出另一个 POST 请求,该请求根据请求中提供的数据创建 PDF 并返回它。 现在的问题是:我如何执行 Post 请求并获取作为附件返回的文件,以便 Spring 可以将其发送回我的前端(Angular)。

到目前为止,我有以下几点:

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

如果有人可以帮助我提供有关如何处理此问题的想法,那就太好了:)

如果您使用的是 spring,请尝试像这样使用RestTemplate

如何使用 Spring 以编程方式使用来自 Rest API 的文件?

暂无
暂无

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

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