2012-05-29 29 views
1

我正在使用HttpClient 4.1下載網頁。我希望得到一個壓縮版本:獲取網頁的壓縮版本

HttpGet request = new HttpGet(url); 
    request.addHeader("Accept-Encoding", "gzip,deflate"); 

    HttpResponse response = httpClient.execute(request,localContext); 
    HttpEntity entity = response.getEntity(); 

response.getFirstHeader("Content-Encoding")顯示然而"Content-Encoding: gzip"entity.getContentEncoding()null

如果我把:

entity = new GzipDecompressingEntity(entity); 

我得到:

java.io.IOException: Not in GZIP format 

它看起來像產生的頁面是純文本,而不是壓縮,即使「內容編碼」標題顯示它的gzip壓縮。

我已經嘗試過這幾個網址(來自不同的網站),但得到相同的結果。

如何獲取網頁的壓縮版本?

+1

如果網站決定不向您發送一個壓縮版本,你不能做任何事情.. – mauris

+5

你是否主動要在代碼中使用壓縮版本?如果你把一個數據包嗅探器放在它上面,你可能會看到數據在被傳回給你之前被HttpClient gzip和解壓縮。 – Iain

回答

1

如果您不希望API處理像解壓縮這樣的普通事情,請不要使用HttpClient。

您可以使用基本URLConnection類來獲取壓縮數據流,通過下面的代碼演示:

public static void main(String[] args) { 
    try { 
     URL url = new URL("http://code.jquery.com/jquery-latest.js"); 
     URLConnection con = url.openConnection(); 
     // comment next line if you want to have something readable in your console 
     con.addRequestProperty("Accept-Encoding", "gzip,deflate"); 
     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     String l; 
     while ((l=in.readLine())!=null) { 
      System.out.println(l); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

這是否意味着HttpClient在響應中自動unzipps實體? –