Android App中进行网络请求,我们都司空见惯。那么进行http请求时可以进行压缩请求,你造么。。。
简介
HTTP定义了一些标准的内容编码类型,并允许用扩展的形式添加更多的编码。
Content-Encoding header 就用这些标准化的代号来说明编码时使用的算法
Content-Encoding值
gzip 表明实体采用GNU zip编码
compress 表明实体采用Unix的文件压缩程序
deflate 表明实体是用zlib的格式压缩的
identity 表明没有对实体进行编码。当没有Content-Encoding header时, 就默认为这种情况
gzip, compress, 以及deflate编码都是无损压缩算法,用于减少传输报文的大小,不会导致信息损失。 其中gzip通常效率最高, 使用最为广泛。
好处
压缩的好处
http压缩对纯文本可以压缩至原内容的40%, 从而节省了60%的数据传输。
使用方式
- 添加头信息
HttpPost httpPost = new HttpPost(MainURL);
httpPost.addHeader("Accept-Encoding", "gzip");
- 解码
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
for (HeaderElement element : ceheader.getElements()) {
if (element.getName().equalsIgnoreCase("gzip")) {
httpResponse.setEntity(new GZipDecompressingEntity(httpResponse.getEntity()));
}
}
}
算了,把我的网络请求方式完整的放出来吧
public static String PostInfo(Context context,List<NameValuePair> subinfo) {
String responseInfo = "";
HttpPost httpPost = new HttpPost(MainURL);
//采用Gzip格式请求
httpPost.addHeader("Accept-Encoding", "gzip");
HttpResponse httpResponse = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(subinfo, HTTP.UTF_8));
HttpClient client = new DefaultHttpClient();
if(context!=null){
//加入cookie
PersistentCookieStore cookieStore= new PersistentCookieStore(context);
((AbstractHttpClient) client).setCookieStore(cookieStore);
// httpPost.setHeader("Cookie",cookieStore.toString());
}
String useragent=(String) client.getParams().getParameter(HttpProtocolParams.USER_AGENT);
client.getParams().setParameter(HttpProtocolParams.USER_AGENT,"chuanyue_app"+useragent);
httpResponse = client.execute(httpPost);
CommonTools.makeLog("useragent", (String) client.getParams().getParameter(HttpProtocolParams.USER_AGENT));
// 连接时间20秒超时
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
// 传输时间30S超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
if(context!=null){
//cookie问题
@SuppressWarnings("unused")
HttpEntity entity = httpResponse.getEntity();
List<Cookie> cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();
PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
for (Cookie cookie:cookies){
myCookieStore.addCookie(cookie);
}
//Gzip解析
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
for (HeaderElement element : ceheader.getElements()) {
if (element.getName().equalsIgnoreCase("gzip")) {
httpResponse.setEntity(new GZipDecompressingEntity(httpResponse.getEntity()));
}
}
}
}
CommonTools.makeLog("response", responseInfo);
responseInfo = EntityUtils.toString(httpResponse.getEntity());
return responseInfo;
}
} catch (Exception e) {
CommonTools.makeLog("post", "PostInfo_Erro");
return "";
}
return "";
}