Reputation: 1744
I am compressing the Json into Gzip format and sending as below:
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);
I want to receive the Post request and decompress that to a string.What @Consumes
annotation i should use for this.
Upvotes: 0
Views: 3134
Reputation: 10961
You can handle gzip-encoding transparent for your resource-classes like described in the docmentation with a ReaderInterceptor
.
The interceptor could look like this:
@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();
}
}
For your resource class the gzipping is transparent. It can still consume application/json
.
You also don't need to handle a byte array, just use a POJO like you would normally do:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response post(Person person) { /* */ }
One problem might also be your client code.
I'm not sure if you are really gzipping the post body so here is a full example that posts a gzipped entity with a 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());
Upvotes: 1