java - Gzip 格式解压缩 - Jersey

标签 java rest jersey jax-rs

我将 Json 压缩为 Gzip 格式并发送如下:

connection.setDoOutput(true); // sets POST method implicitly
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Encoding", "gzip"); 

final byte[] originalBytes = body.getBytes("UTF-8"); 
final ByteArrayOutputStream baos = new ByteArrayOutputStream(originalBytes.length);
final ByteArrayEntity postBody = new ByteArrayEntity(baos.toByteArray());                       
method.setEntity(postBody);

我想接收 Post 请求并将其解压缩为字符串。为此我应该使用什么 @Consumes 注释。

最佳答案

您可以对资源类透明地处理 gzip 编码,例如 described in the docmentation使用ReaderInterceptor。 拦截器可能如下所示:

@Provider
public class GzipReaderInterceptor implements ReaderInterceptor {

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context)  throws IOException, WebApplicationException {
        if ("gzip".equals(context.getHeaders().get("Content-Encoding"))) {
            InputStream originalInputStream = context.getInputStream();
            context.setInputStream(new GZIPInputStream(originalInputStream));
        }
        return context.proceed();
    }

}

对于您的资源类,gzip 压缩是透明的。它仍然可以使用 application/json。 您也不需要处理字节数组,只需像通常那样使用 POJO:

@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response post(Person person) { /* */ }

一个问题也可能是您的客户端代码。 我不确定您是否真的对帖子正文进行了 gzip 压缩,因此这里是一个完整的示例,它使用 URLConnection 发布 gzip 压缩的实体:

String entity = "{\"firstname\":\"John\",\"lastname\":\"Doe\"}";

ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write(entity.getBytes("UTF-8"));
gzos.close();

URLConnection connection = new URL("http://whatever").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Encoding", "gzip");
connection.connect();
baos.writeTo(connection.getOutputStream());

关于java - Gzip 格式解压缩 - Jersey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25542450/

相关文章:

java - 如何使用 gson 反序列化未知命名数组 json

java - 如何将时间从 java.util.Date 存储到 java.sql.Date

java - 为什么错误的路径注释不会使 Jersey 的 REST API 崩溃?

rest - 如何在 CXF 中向 JAXBContext 添加其他类

java - 不使用 Http-Authentication 在 Apache Jersey 中进行身份验证?

java - 如何在不提供完整路径名的情况下从 intelliJ IDEA 中的资源文件夹访问图像

java - 通过 JDBC 获取 JList 中的数据 - 缺失的链接

php - 生成基本 OAuth header

java - 具有 SSL 相互身份验证的 Jersey 客户端

java - 如何使用 Jersey 将带注释的对象列表从客户端传递到服务器