说明:现在很多网站都会在回传数据的时候进行GZIP压缩,我们可以在请求头中申明支持GZIP压缩。可以减轻网络传输压力,Xutils中已经实现。
下面是一个DEMO,便于理解。
private void initGzip() {
findViewById(R.id.btn1).setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
new Thread(new Runnable() { @Override
public void run() { try {
boolean isGzip = false; // 初始化httpClient对象
DefaultHttpClient httpClient = new DefaultHttpClient(); // 初始化httpGe对象
HttpGet get = new HttpGet("http://mobileif.maizuo.com/city");
// 1.发送请求头:`Accept-Encoding:gzip`
get.addHeader("Accept-Encoding", "gzip"); // HttpGet get = new HttpGet("http://httpbin.org/gzip"); // 发起请求
HttpResponse response = httpClient.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
// 2. 取的响应头`Content-Encoding`,判断是否包含Content-Encoding:gzip
Header[] headers = response.getHeaders("Content-Encoding");
for (Header header : headers) {
String value = header.getValue();
if (value.equals("gzip")) {
isGzip = true;
}
} // 3.相应的解压
String result;
HttpEntity entity = response.getEntity();
if (isGzip) {// gzip解压
InputStream in = entity.getContent(); GZIPInputStream gzipIn = new GZIPInputStream(in); // inputStream-->string
result = convertStreamToString(gzipIn);
} else {// 标准解压 // 打印响应结果
result = EntityUtils.toString(entity);
}
System.out.println("result:" + result);
} } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}).start();
}
}); } public static String convertStreamToString(InputStream is) throws IOException {
try {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
// BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while ((line = reader.readLine()) != null) {
// sb.append(line);
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
} catch (Exception e) {
e.printStackTrace();
return "";
} }