我有一个下面的类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);
}
太棒了!我忽略了那个。谢谢 ;) – svenkapudija