簡體   English   中英

解壓縮GZIP http-response(使用jersey client api,java)

[英]Uncompress GZIP http-response (using jersey client api, java)

有人可以告訴我在從某些Http調用獲得響應時解壓縮GZIP內容需要做些什么。

要撥打電話我使用Jersey客戶端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;
  • 如果沒有,請在String中正常處理; if,so解壓縮並獲取String中的內容

只需將GZIPContentEncodingFilter添加到您的客戶端:

client.addFilter(new GZIPContentEncodingFilter(false));

不要將響應檢索為實體。 將其作為輸入流檢索並將其包裝在java.util.zip.GZIPInputStream中:

GZipInputStream is = new GZipInputStream(response.getEntityInputStream());

然后自己讀取未壓縮的字節並將其轉換為String。

另外,檢查服務器是否包含HTTP頭Content-Encoding: gzip 如果沒有,請嘗試將其包含在響應中。 也許澤西島足夠聰明,可以做正確的事情。

在Jersey 2.x(我使用2.26):

WebTarget target = ...
target.register(GZipEncoder.class);

然后getEntity(String.class)往常一樣在響應上使用getEntity(String.class)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM