2011-07-03 91 views
0

我有一個下面的類HTTPGET - 怪異編碼/字符

public class MyHttpClient { 
private static HttpClient httpClient = null; 

public static HttpClient getHttpClient() { 
    if (httpClient == null) 
     httpClient = new DefaultHttpClient(); 

    return httpClient; 
} 

public static String HttpGetRequest(String url) throws IOException { 
    HttpGet request = new HttpGet(url); 
    HttpResponse response = null; 
    InputStream stream = null; 

    String result = ""; 
    try { 
     response = getHttpClient().execute(request); 
     if (response.getStatusLine().getStatusCode() != 200) 
      response = null; 
     else 
      stream = response.getEntity().getContent(); 

      String line = ""; 
      StringBuilder total = new StringBuilder(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(stream)); 
      while ((line = rd.readLine()) != null) { 
       total.append(line); 
      } 

      // Return full string 
      result = total.toString(); 
    } catch (ClientProtocolException e) { 
     response = null; 
     stream = null; 
     result = null; 
    } catch (IllegalStateException e) { 
     response = null; 
     stream = null; 
     result = null; 
    } 

    return result; 
} 
} 

和web服務,其響應頭(我不能提供的,因爲隱私直接鏈路)

狀態:HTTP/1.1 200

行緩存控制:私人

Content-Type:application/json;

字符集= UTF-8

內容編碼:gzip

服務器:IIS/7.5

X-AspNetMvc-版本:3.0

X-ASPNET-版本: 4.0.30319

X-Powered-by:ASP.NET

Date:Su N,03

2011年7月11點00分43秒GMT

連接:關閉

的Content-Length:8134

最後我得到的結果是一系列怪異,難以理解的字符(我應該定期使用JSON,就像我在普通桌面瀏覽器中看到的一樣)。

問題出在哪裏?(對於實例相同的代碼google.com完美的作品,我也得到不錯的結果)

編輯:解決方案(見下文說明) 更換

HttpGet request = new HttpGet(url); 

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

和替換

stream = response.getEntity().getContent(); 

stream = response.getEntity().getContent(); 
Header contentEncoding = response.getFirstHeader("Content-Encoding"); 
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
    stream = new GZIPInputStream(stream); 
} 

回答

3

的問題是在這裏:

Content-Encoding: gzip 

這意味着你得到奇怪的字符是預期的JSON的gzip壓縮版本。您的瀏覽器會執行解壓縮,以便您可以看到解碼結果。你應該看看你的請求頭和服務器的配置。

+0

太棒了!我忽略了那個。謝謝 ;) – svenkapudija

3

那麼,gzip編碼通常是很好的做法 - 對於JSON數據(特別是大數據),它實際上可以減少10倍到20倍的數據傳輸量(這是一件好事)。所以更好的是讓HttpClient很好地處理GZIP壓縮。例如這裏:

http://forrst.com/posts/Enabling_GZip_compression_with_HttpClient-u0X

BTW。但在服務器端,當客戶端沒有說「Accept-Encoding:gzip」時,提供GZIP壓縮數據似乎是錯誤的,這似乎是這樣的...所以有些事情也必須在服務器上進行更正。上面的例子爲你添加了Accept-Encoding標題。