Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable gzip compression for content encoding with Jersey (JAX-RS 2.0) client?

I have a Java application that uses the Jersey implementation of JAX-RS 2.0 and I want to enable gzip compression on the client side. The server has it enabled and I have verified that by looking in Chrome at the "Size/Content" in the Developer Tools for the specific URL the client is using.

I see a lot of information and documentation floating around the web about setting the HTTP Headers with filters and decoding response bodies with interceptors and I cannot decipher what I actually need to code in the client.

I have this code:

private synchronized void initialize() {
    Client client = ClientBuilder.newClient();
    client.register(new HttpBasicAuthFilter(username, password));
    WebTarget targetBase = client.target(getBaseUrl());
    ...
}

What should I add to enable compression?

like image 532
Jason Avatar asked Mar 19 '14 22:03

Jason


2 Answers

Instead of registering EncodingFilter and GZipEncoder individually you can use EncodingFeature directly. With Jersey 2.32 I had problems with incomplete injections and resulting NullPointerExceptions otherwise.

Client client = ClientBuilder.newClient();
client.register(new EncodingFeature("gzip", GZipEncoder.class));
client.register(new HttpBasicAuthFilter(username, password));
WebTarget targetBase = client.target(getBaseUrl());

Note the difference between setting the useEncoding parameter

client.register(new EncodingFeature("gzip", GZipEncoder.class));

or not

client.register(new EncodingFeature(GZipEncoder.class));

is if the initial request by the client is already gzip encoded or if it merely indicates to the server, that it will understand a compressed reply.

like image 171
Joe23 Avatar answered Sep 18 '22 14:09

Joe23


managed to do it with:

private synchronized void initialize() {
    Client client = ClientBuilder.newClient();
    client.register(new HttpBasicAuthFilter(username, password));
    client.register(GZipEncoder.class);
    client.register(EncodingFilter.class);
    WebTarget targetBase = client.target(getBaseUrl());
    ...
}

Pretty much the same as @Jason, but EncodingFilter detects the GzipEncoder for me.

like image 37
Jayen Avatar answered Sep 18 '22 14:09

Jayen