Use gzip to compress the interface messages to save traffic.

Source: Internet
Author: User

Gziputil compression and pressurization tools

/*** Compressed string ** @ Param Str * @ Param Charest * @ return * @ throws ioexception * @ throws unsupportedencodingexception */public static byte [] compress (string STR, string charset) throws ioexception, unsupportedencodingexception {assert. notnull (STR, "null compress error"); bytearrayoutputstream out = new bytearrayoutputstream (); gzipoutputstream gzip = new gzipoutputstream (out); try {gzip. write (Str. getbytes (charset); gzip. close (); Return out. tobytearray ();} catch (exception e) {Throw new ioexception (E);} finally {fileutil. close (gzip); fileutil. close (out );}}

/*** Extract the string * @ Param Str * @ Param Charest * @ return * @ throws ioexception * @ throws unsupportedencodingexception * @ throws filenotfoundexception */public static byte [] uncompress (inputstream in) throws ioexception, timeout, bytes {bytearrayoutputstream out = new bytearrayoutputstream (); gzipinputstream gunzip = new gzipinputstream (in); try {byte [] buffer = new byte [256]; int N; while (n = gunzip. read (buffer)> = 0) {out. write (buffer, 0, n);} return out. tobytearray ();} catch (exception e) {Throw new ioexception (E);} finally {fileutil. close (out); fileutil. close (gunzip); fileutil. close (in );}}
Controller compresses data and uses httpservletresponse response to output data

byte[] _byte=GzipUtil.compress(json,"UTF-8");response.getOutputStream().write(_byte);response.getOutputStream().flush();response.getOutputStream().close();


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.