2014-08-28 42 views
0

我压缩JSON转换成gzip格式,并如下发送: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请求,并解压缩到一个string.What @Consumes注释我应该为此使用。

回答

1

您可以使用ReaderInterceptordescribed 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()); 
+0

感谢...但如何处理从拦截器的返回值方法。 – 2014-08-28 13:04:27

+0

它会是这样的..... public String Gzip(byte [] json){ String str = ... //很长的字符串 return str; } – 2014-08-28 13:05:38

+0

我更新了我的答案。 – lefloh 2014-08-28 16:49:32