【问题标题】:Spring - Doing a Post Request to a Rest Endpoint which returns a fileSpring - 向返回文件的 Rest Endpoint 发出 Post 请求
【发布时间】:2020-10-19 15:43:36
【问题描述】:

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

我有一个 Spring 应用程序,我从前端收到一个 POST 请求(只知道 spring 应用程序的端点)。然后控制器应该向另一个 API 发出另一个 POST 请求,该 API 根据请求中提供的数据创建 PDF 并返回它。现在的问题是:我如何进行发布请求并获取作为附件返回的文件,以便 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;
    }

如果有人能帮助我解决这个问题,那就太好了:)

【问题讨论】:

    标签: java spring rest


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多