如何使用Jersey(JAX-RS 2.0)客户端为内容编码启用gzip压缩? [英] How to enable gzip compression for content encoding with Jersey (JAX-RS 2.0) client?
问题描述
我有一个使用JAX-RS 2.0的Jersey实现的Java应用程序,并且我想在客户端启用gzip压缩.服务器已启用它,并且通过在Chrome中的开发人员工具中的大小/内容"中查找客户端正在使用的特定URL,我已经进行了验证.
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.
我看到网上有很多信息和文档,内容涉及设置带有过滤器的HTTP标头和带有拦截器的响应主体解码,而我无法解读客户端中实际需要编写的代码.
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.
我有此代码:
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?
推荐答案
修改为:
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");
...
}
在此示例中,有一些我未在示例中引用的字段和方法(例如MEDIA_TYPE
),您必须自己弄清楚这些字段和方法.应该很简单.
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.
我通过分析响应头并监视应用程序网络使用情况来验证了此工作.根据我所做的网络使用情况检查,我得到了10:1的压缩比.没错,是的!
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!
这篇关于如何使用Jersey(JAX-RS 2.0)客户端为内容编码启用gzip压缩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!