解压缩 GZIP http 响应(使用 jersey 客户端 api、java)
有人可以告诉我在从某些 Http 调用获取响应时需要做什么才能解压缩 GZIP 内容吗?
为了进行调用,我使用 Jersey Client API,请参阅下面的代码:
String baseURI = "http://api.stackoverflow.com/1.1/answers/7539863?body=true&comments=false";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource wr = client.resource(baseURI);
ClientResponse response = null;
response = wr.get(ClientResponse.class);
String response_data = response.getEntity(String.class);
System.out.println(response_data);
但是输出是 GZIP 的,看起来像:
{J?J??t??`$?@??????....
如果我可以实现以下功能,那就太好了:
- 能够检测内容是否是 GZIP 的;
- 如果不是,则像普通字符串一样处理; if, so 解压得到String中的内容
Could someone tell me what I need to do in order to uncompress a GZIP content when getting the response from some Http-call.
To make the call I use the Jersey Client API, see code below:
String baseURI = "http://api.stackoverflow.com/1.1/answers/7539863?body=true&comments=false";
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource wr = client.resource(baseURI);
ClientResponse response = null;
response = wr.get(ClientResponse.class);
String response_data = response.getEntity(String.class);
System.out.println(response_data);
However the output is GZIP’d and looks like:
{J?J??t??`$?@??????....
It would be good if I could implement the following:
- being able to detect whether content is GZIP’d or not;
- If not, process like normal in a String; if, so uncompress and get the content in String
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需将 GZIPContentEncodingFilter 添加到您的客户端:
Simply add GZIPContentEncodingFilter to your client:
不要将响应作为实体检索。将其作为输入流检索并将其包装在 java.util.zip.GZIPInputStream 中:
然后自己读取未压缩的字节并将其转换为字符串。
另外,检查服务器是否包含 HTTP 标头
Content-Encoding: gzip
。如果没有,请尝试将其包含在响应中。也许泽西岛足够聪明,能够做正确的事。Don't retrieve the response as an entity. Retrieve it as an input stream and wrap it in a java.util.zip.GZIPInputStream:
Then read the uncompressed bytes yourself and turn it into a String.
Also, check whether the server is including the HTTP header
Content-Encoding: gzip
. If not, try including it in the response. Perhaps Jersey is smart enough to do the right thing.在 Jersey 2.x 中(我使用 2.26):
然后可以像往常一样在响应上使用
getEntity(String.class)
。In Jersey 2.x (I use 2.26):
Then
getEntity(String.class)
can be used on the response as usual.