【问题标题】:Download pdf from response (okHttp3) - JAVA spring boot / display on browser从响应(okHttp3)下载pdf - JAVA spring boot / 在浏览器上显示
【发布时间】:2021-06-24 16:49:54
【问题描述】:

我正在使用外部 API,当我执行返回 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 时,如何将响应返回为 pdf 下载?给客户?我应该返回哪个对象?

我的代码:

    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");

感谢您的帮助。 伊丹,

【问题讨论】:

标签: java spring pdf itext


【解决方案1】:

路径 path = Paths.get("https://api.worldota.net/api/b2b/v3/hotel/order/document/voucher/download/?data={"partner_order_id":"" + partner_order_id + "","language":"" + language + ""}"); 字节[] 数据 = Files.readAllBytes(path); ByteArrayResource 资源 = new ByteArrayResource(data);

    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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多