您可以使用ReaderInterceptor
为described in the docmentation等资源类处理透明的gzip编码。 拦截器看起来是这样的:
@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压缩后的身体所以这里是一个完整的例子帖子gzip压缩实体与URLConnection
:
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());
感谢...但如何处理从拦截器的返回值方法。 – 2014-08-28 13:04:27
它会是这样的..... public String Gzip(byte [] json){ String str = ... //很长的字符串 return str; } – 2014-08-28 13:05:38
我更新了我的答案。 – lefloh 2014-08-28 16:49:32