从响应下载 pdf (okHttp3) - JAVA spring 启动/在浏览器上显示
Download pdf from response (okHttp3) - JAVA spring boot / display on browser
我正在使用外部 API,当我执行 returns pdf 的请求之一时,我无法在服务器端处理它。
如果我复制粘贴 api 请求:
https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={"partner_order_id":“0d7836b4-2eba-475f-b2d6-1b95092534b0”,“语言”:“en”}
浏览器在浏览器中打开一个pdf并下载。
当我在 java 代码中执行此 url 时,我如何 return 响应作为 pdf 下载?给客户?我应该 return 哪个对象?
我的代码:
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.addInterceptor(new BasicAuthInterceptor("api-key", "api-key")).build();
Request request = new Request.Builder().url(
"https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={\"partner_order_id\":\""
+ partner_order_id + "\",\"language\":\"" + language + "\"}")
.method("GET", null).addHeader("Content-Type", "application/pdf").build();
Response response = client.newCall(request).execute();
response.close();
} catch (Exception e) {
}
return ResponseEntity.ok("downloaded completed");
感谢您的帮助。
伊丹,
路径path = Paths.get("https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={"partner_order_id":""
+ partner_order_id + "","语言":"" + 语言 + ""}");
byte[] 数据 = Files.readAllBytes(路径);
ByteArrayResource 资源 = new ByteArrayResource(数据);
return ResponseEntity.ok()
// Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + path.getFileName().toString())
// Content-Type
.contentType(mediaType) //
// Content-Lengh
.contentLength(data.length) //
.body(resource);
我正在使用外部 API,当我执行 returns pdf 的请求之一时,我无法在服务器端处理它。
如果我复制粘贴 api 请求: https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={"partner_order_id":“0d7836b4-2eba-475f-b2d6-1b95092534b0”,“语言”:“en”}
浏览器在浏览器中打开一个pdf并下载。 当我在 java 代码中执行此 url 时,我如何 return 响应作为 pdf 下载?给客户?我应该 return 哪个对象?
我的代码:
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.addInterceptor(new BasicAuthInterceptor("api-key", "api-key")).build();
Request request = new Request.Builder().url(
"https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={\"partner_order_id\":\""
+ partner_order_id + "\",\"language\":\"" + language + "\"}")
.method("GET", null).addHeader("Content-Type", "application/pdf").build();
Response response = client.newCall(request).execute();
response.close();
} catch (Exception e) {
}
return ResponseEntity.ok("downloaded completed");
感谢您的帮助。 伊丹,
路径path = Paths.get("https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={"partner_order_id":"" + partner_order_id + "","语言":"" + 语言 + ""}"); byte[] 数据 = Files.readAllBytes(路径); ByteArrayResource 资源 = new ByteArrayResource(数据);
return ResponseEntity.ok()
// Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + path.getFileName().toString())
// Content-Type
.contentType(mediaType) //
// Content-Lengh
.contentLength(data.length) //
.body(resource);