使用 JERSEY 的输入和输出二进制流? [英] Input and Output binary streams using JERSEY?

查看:48
本文介绍了使用 JERSEY 的输入和输出二进制流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jersey 来实现一个 RESTful API,该 API 主要用于检索和提供 JSON 编码的数据.但是在某些情况下,我需要完成以下操作:

I'm using Jersey to implement a RESTful API that is primarily retrieve and serve JSON encoded data. But I have some situations where I need to accomplish the following:

  • 导出可下载的文档,例如 PDF、XLS、ZIP 或其他二进制文件.
  • 检索多部分数据,例如一些 JSON 和上传的 XLS 文件

我有一个基于 JQuery 的单页 Web 客户端,它创建对该 Web 服务的 AJAX 调用.目前,它不执行表单提交,而是使用 GET 和 POST(使用 JSON 对象).我应该使用表单帖子发送数据和附加的二进制文件,还是可以使用 JSON 和二进制文件创建多部分请求?

I have a single-page JQuery-based web client that creates AJAX calls to this web service. At the moment, it doesn't do form submits, and uses GET and POST (with a JSON object). Should I utilize a form post to send data and an attached binary file, or can I create a multipart request with JSON plus binary file?

我的应用程序的服务层在生成 PDF 文件时当前会创建一个 ByteArrayOutputStream.通过 Jersey 将此流输出到客户端的最佳方式是什么?我创建了一个 MessageBodyWriter,但我不知道如何从 Jersey 资源中使用它.这是正确的方法吗?

My application's service layer currently creates a ByteArrayOutputStream when it generates a PDF file. What is the best way to output this stream to the client via Jersey? I've created a MessageBodyWriter, but I don't know how to use it from a Jersey resource. Is that the right approach?

我一直在查看 Jersey 中包含的示例,但还没有找到任何说明如何执行这些操作的任何内容.如果重要的话,我正在使用 Jersey 和 Jackson 来执行 Object->JSON 而没有 XML 步骤,并且并没有真正使用 JAX-RS.

I've been looking through the samples included with Jersey, but haven't found anything yet that illustrates how to do either of these things. If it matters, I'm using Jersey with Jackson to do Object->JSON without the XML step and am not really utilizing JAX-RS.

推荐答案

通过扩展 StreamingOutput 对象,我设法获得了 ZIP 文件或 PDF 文件.下面是一些示例代码:

I managed to get a ZIP file or a PDF file by extending the StreamingOutput object. Here is some sample code:

@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
    return new StreamingOutput() {
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                PDFGenerator generator = new PDFGenerator(getEntity());
                generator.generatePDF(output);
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}

PDFGenerator 类(我自己的用于创建 PDF 的类)从 write 方法获取输出流并写入该输出流,而不是新创建的输出流.

The PDFGenerator class (my own class for creating the PDF) takes the output stream from the write method and writes to that instead of a newly created output stream.

不知道这是否是最好的方法,但它有效.

Don't know if it's the best way to do it, but it works.

这篇关于使用 JERSEY 的输入和输出二进制流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆