Introduction:
Reprinted please indicate from: http://blog.csdn.net/icyfox_bupt/article/details/9572813
Android software development requires dealing with data on the network. To make the software that users love, we need to find every way to reduce the download traffic and speed up the download.
Gzip is an existing website compression format. As long as the website supports gzip, we can download compressed data packets from the website.
Gzip Introduction Please see Baidu Encyclopedia: http://baike.baidu.com/view/966625.htm
Enable gzip:
Enabling gzip communication requires support from both the server and the client, and gzip must be enabled for the server (For details, refer to the method for enabling gzip in IIS In win2003), which will increase the burden on some servers.
If the server is not set up by you, you don't have to worry about it.
On the client side, when making an HTTP request, add the following content to the HTTP header:
Accept-encoding: gzip, deflate
If the server supports this, the header of the returned data packet will include:
Accept-encoding: gzip, deflate
Decompress gzip:
UseCodeThe following function uses the get method to obtain the data on the network, and then uses the gzipinputstream class to understand the pressure on the gzip data. And returns the resulting string:
Public String get (string URL) {httpget get = new httpget (URL); httpclient client = new defaulthttpclient (); get. addheader ("Accept-encoding", "gzip, deflate"); // Add the GZIP format httpresponse response = NULL to the header; bytearraybuffer bt = new bytearraybuffer (4096 ); string resultstring = "" Maid response=client.exe cute (get); // run the get method httpentity He = response. getentity (); // The following is the decompression process gzipinputstream GIS = new gzipinputstream (HE. getco Ntent (); int L; byte [] TMP = new byte [4096]; while (L = GIS. Read (TMP ))! =-1) {BT. append (TMP, 0, L);} resultstring = new string (BT. tobytearray (), "UTF-8"); // The following parameters are replaced by the website encoding in general are UTF-8} catch (exception e) {log. I ("Err", E. tostring (); // throw an exception in processing} return resultstring ;}
The above code is relatively simple and I will not explain it much. (In fact, I am also confused) The idea is from http://bbs.csdn.net/topics/340021298.ArticleFor more information, see.
If you don't quite understand how to copy the above code, you can also use it as a get function.
although the code is simple, the gzip effect cannot be underestimated. For common web pages, the compressed data is usually 1/2 ~ 2/3. For some highly redundant data, such as Weibo and Forum APIs, the API data can even reach 1/4. This is very impressive for provincial traffic.