2011-07-03 33 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标题。