[英]Spring - Doing a Post Request to a Rest Endpoint which returns a file
[英]Java/Spring - Send Post Request to retrieve a PDF-File from anoter Rest Endpoint
我想在 Java 中做一个简单的 POST-Http-Request,用一个对象作为有效负载(序列化为 JSON - 我有 Gson 库)。 端点根据请求的 JSON-Payload 检索 PDF 文件。
当我与 Postman 一起尝试时,PDF 被正确检索。 但是我怎么能在java中做到这一点,甚至从我的函数中返回文件呢?
这是我到目前为止的代码,请求似乎正在运行,但它似乎没有任何有效负载:
@PostMapping(path = "/print")
public String printCompetences(@RequestBody final PrintCompetences competences)
throws IOException, InterruptedException {
Gson gson = new Gson();
String requestPayLoad = gson.toJson(competences);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:5001"))
.POST(HttpRequest.BodyPublishers.ofString(requestPayLoad))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
return gson.toJson(response.body());
}
一种选择是将字节流式传输到HttpServletResponse
。 如果您将方法声明更改为:
@PostMapping(path = "/print", produces = MediaType.APPLICATION_PDF_VALUE)
public String printCompetences(@RequestBody final PrintCompetences competences,
HttpServletResponse servletResponse)
throws IOException, InterruptedException {
您可以将 pdf 字节直接流式传输到servletResponse
例如:
// Not String but InputStream. ByteArray might work also for binary but why not to stream
HttpResponse<InputStream> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
// I use here Apache commons IOUtils to write bytes
IOUtils.copy(response.body(), servletResponse.getOutputStream());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.