在Jersey Rest Service中发送文件和元数据

时间:2014-11-11 11:25:48

标签: rest jersey

我需要使用Jersey 2.0创建ReST服务。我需要向客户端发送多个文档和元数据。 实现这一目标的最佳方法是什么。

我能够从服务器发送MultiPart响应,但不知道如何从客户端代码中读取它

1 个答案:

答案 0 :(得分:0)

假设您有一个名为“document1”的文档,您希望通过该客户端获取该文档。 在REST-API中,文档(资源)的唯一标识符可以是:

http://example.com/restapi/documents/document1

如果您想读取数据,请对该uri执行HTTP-GET请求。 这里有一个重要的部分:资源可以有多种表示 - 元数据和二进制数据。

因此客户端必须告诉服务器获取哪种表示类型(内容协商)。例如,可以在客户端请求的ACCEPT Header中设置此信息。 您可以使用内容类型“application / json”作为元数据的表示。

很遗憾,您没有告诉我们您要发送哪种二进制数据。 如果它们是PDF,则内容类型将是“application / pdf”。如果二进制数据没有特定类型,则可以使用“application / octet-stream”。

当然,在服务器端也有工作要做。这是一个例子:

@Path("/documents/{documentname}")
public class docResource {

    @GET @Produces("application/json")
    public Response getDocumentMetaData(@PathParam("documentname") String docName) {
        // Create a Response containing a json
    }
    @GET @Produces("application/pdf")
    public Response getDocumentBinaryData(@PathParam("documentname") String docName) {
        // Create a response containing the binary data
    }

    ...
}

Jersey将检查客户端的accept标头,并运行相应的方法。 另请参阅:https://jersey.java.net/documentation/latest/jaxrs-resources.html

如果您使用杰克逊的球衣,您也可以轻松地将POJO编组为JSON,反之亦然: http://examples.javacodegeeks.com/enterprise-java/rest/jersey/json-example-with-jersey-jackson/

如果你不确定在“getDocumentBinaryData”中做什么 - 方法 - 从mkyong查看这个简单的例子: http://www.mkyong.com/webservices/jax-rs/download-excel-file-from-jax-rs/