![](/img/trans.png)
[英]Java/Spring - Send Post Request to retrieve a PDF-File from anoter Rest Endpoint
[英]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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.