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

為{幸葍}努か 提交于 2019-12-06 00:00:34

问题


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?


回答1:


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.




回答2:


Modify to look like:

private synchronized void initialize() {
    Client client = ClientBuilder.newClient();
    client.register(new HttpBasicAuthFilter(username, password));
    client.register(GZipEncoder.class);
    WebTarget targetBase = client.target(getBaseUrl());
    ...
    // new lines here:
    Invocation.Builder request = targetBase.request(MEDIA_TYPE);
    request.header(HttpHeaders.ACCEPT_ENCODING, "gzip");
    ...
}

In this example, there are some fields and methods being referenced that I don't include in the example (such as MEDIA_TYPE), you'll have to figure those out yourself. Should be pretty straight forward.

I verified this worked by analyzing the response headers and monitoring the application network usage. I got a 10:1 compression ration according to the network usage checks I did. That seems about right, yay!




回答3:


In my example (with JAX RS 2.x) and Jersey where multipart is being used, none of the above worked but this did:

Client client = ClientBuilder.newBuilder()
            .register(EncodingFilter.class)
            .register(GZipEncoder.class)
            .property(ClientProperties.USE_ENCODING, "gzip")
            .register(MultiPartFeature.class)
            .register(LoggingFilter.class)
            .build();

Essentially same as the above answers but had to add that one property for "gzip".



来源:https://stackoverflow.com/questions/22519642/how-to-enable-gzip-compression-for-content-encoding-with-jersey-jax-rs-2-0-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!