Android Gzip/zip Compression

Source: Internet
Author: User

Objective:

Have done the Android network development know, in the network transmission we generally will turn on GZIP compression, but out of the nature of inquisitive only know how to open can not satisfy my curiosity, so think to write a demo test the more commonly used two data compression method, Gzip/zip compression.

First meet the gzip compression

Gzip is a website compression acceleration of a technology, for the opening can speed up the speed of our website, the principle is through the server compression, client browser Rapid decompression principle, can greatly reduce the flow of the website. Gzip was first created by Jean-loup Gailly and Mark Adler for file compression for UNIX systems. We often use files with the. gz suffix in Linux, which are in gzip format. Nowadays it has become a very popular data compression format, or a file format, used on the Internet. GZIP encoding on the HTTP protocol is a technique used to improve the performance of Web applications. High-traffic Web sites often use gzip compression technology to make users feel faster. This generally refers to the WWW server installed in a feature, when someone to access the server's website, the server of this feature will compress the content of the Web page to be displayed in the browser of the visiting computer. Generally, the plain text content can be compressed to 40% of the original size. So the transmission is fast, The effect is that when you click on the URL, it will show up quickly. This, of course, increases the load on the server. The function module is installed in the general server.

What are the benefits of opening gzip? when Gzip is turned on, the data exported to the user's browser is compressed, which reduces the amount of data transmitted over the network and improves the speed of browsing.

So how do you compress on Android? Related Compression API See Http://www.apihome.cn/api/android/java.util.zip

   /*** Gzip Compressed data * *@paramUngzipstr *@return     */     Public Staticstring Compressforgzip (String ungzipstr) {if(Textutils.isempty (ungzipstr)) {return NULL; }        Try{bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Gzipoutputstream gzip=NewGzipoutputstream (BAOs);            Gzip.write (Ungzipstr.getbytes ());            Gzip.close (); byte[] encode =Baos.tobytearray ();            Baos.flush ();            Baos.close (); returnBase64encoder.encode (encode); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        return NULL; }    /*** Gzip Extract data * *@paramGzipstr *@return     */     Public Staticstring Decompressforgzip (String gzipstr) {if(Textutils.isempty (gzipstr)) {return NULL; }        byte[] t =base64decoder.decodetobytes (GZIPSTR); Try{Bytearrayoutputstream out=NewBytearrayoutputstream (); Bytearrayinputstream in=NewBytearrayinputstream (t); Gzipinputstream gzip=NewGzipinputstream (in); byte[] buffer =New byte[buffersize]; intn = 0;  while((n = gzip.read (buffer, 0, buffer.length)) > 0) {out.write (buffer,0, N);            } gzip.close ();            In.close ();            Out.close (); returnout.tostring (); } Catch(IOException e) {e.printstacktrace (); }        return NULL; }

And then we'll meet again. Zip compression

Zip, a compression algorithm for computer files, formerly known as deflate (vacuum), was invented by Fille Katz (Phil Katz), and he published the information in that format in January 1989. Zip usually uses the suffix name ". zip", which is in MIME format application/zip. Currently, the zip format belongs to one of several mainstream compression formats, and its competitors include the RAR format and the open source 7-zip format. Compared to the performance, the RAR format is higher than the compression rate in the ZIP format, and 7-zip has been applied in more fields due to the free compression tool.

Look at the specific implementation:

 /*** Zip Compressed data * *@paramUnzipstr *@return     */     Public Staticstring Compressforzip (String unzipstr) {if(Textutils.isempty (unzipstr)) {return NULL; }        Try{bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Zipoutputstream Zip=NewZipoutputstream (BAOs); Zip.putnextentry (NewZipEntry ("0"));            Zip.write (Unzipstr.getbytes ());            Zip.closeentry ();            Zip.close (); byte[] encode =Baos.tobytearray ();            Baos.flush ();            Baos.close (); returnBase64encoder.encode (encode); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        return NULL; }    /*** Zip Extract data * *@paramZipstr *@return     */     Public Staticstring Decompressforzip (String zipstr) {if(Textutils.isempty (zipstr)) {return NULL; }        byte[] t =base64decoder.decodetobytes (ZIPSTR); Try{Bytearrayoutputstream out=NewBytearrayoutputstream (); Bytearrayinputstream in=NewBytearrayinputstream (t); Zipinputstream Zip=NewZipinputstream (in);            Zip.getnextentry (); byte[] buffer =New byte[buffersize]; intn = 0;  while((n = zip.read (buffer, 0, buffer.length)) > 0) {out.write (buffer,0, N);            } zip.close ();            In.close ();            Out.close (); returnOut.tostring ("UTF-8"); } Catch(IOException e) {e.printstacktrace (); }        return NULL; }

Write an example to test the effect:

List<person> personlist =NewArraylist<>(); intTestmaxcount = 500;//maximum number of data bars tested//Add test Data         for(inti = 0; i < Testmaxcount; i++) { person person=NewPerson ();            Person.setage (i);            Person.setname (string.valueof (i));        Personlist.add (person); }        //Fastjson generating JSON dataString Jsondata =Jsonutils.objecttojsonforfastjson (personlist); LOG.E ("Mainactivity", "pre-compress JSON data---->" +jsondata); LOG.E ("Mainactivity", "JSON data length before compression---->" +jsondata.length ()); //gzip Compression        LongStart =System.currenttimemillis (); String Gzipstr=Ziputils.compressforgzip (Jsondata); LongEnd =System.currenttimemillis (); LOG.E ("Mainactivity", "gzip compression time cost---->" + (End-start)); LOG.E ("Mainactivity", "gzip compressed JSON data---->" +gzipstr); LOG.E ("Mainactivity", "gzip compressed JSON data length---->" +gzipstr.length ()); //gzip UnzipStart =System.currenttimemillis (); String Ungzipstr=Ziputils.decompressforgzip (GZIPSTR); End=System.currenttimemillis (); LOG.E ("Mainactivity", "gzip decompression time Cost---->" + (End-start)); LOG.E ("Mainactivity", "gzip extracted JSON data---->" +ungzipstr); LOG.E ("Mainactivity", "gzip uncompressed JSON data length---->" +ungzipstr.length ()); //Zip compressionStart =System.currenttimemillis (); String Zipstr=Ziputils.compressforzip (Jsondata); End=System.currenttimemillis (); LOG.E ("Mainactivity", "Zip compression time Cost---->" + (End-start)); LOG.E ("Mainactivity", "Zip compressed JSON data---->" +zipstr); LOG.E ("Mainactivity", "Zip compressed JSON data length---->" + zipstr.length ());

Run time-consuming comparisons:

Comparison of data compression ratios:

It can be seen from above that both compression efficiency and compression ratio are comparable. Maybe I'm testing a little bit of data.

Next look at how to turn on network gzip compression

In the Android client request header, add "accept-encoding", "gzip", to allow the server to transmit gzip data.

Specific implementation here no longer do a specific introduction to share a link: http://blog.csdn.net/kepoon/article/details/7482096

Android Gzip/zip Compression

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.