Can I compress HTTP Requests using GZIP?

Kevin Boyd picture Kevin Boyd · Sep 20, 2009 · Viewed 16.7k times · Source

I am communicating to a Tomcat Server using a Java ME application on my mobile device.
I was wondering if I could compress my requests/responses using Gzip to reduce the number of bytes sent over the network.

Answer

ZZ Coder picture ZZ Coder · Sep 20, 2009

Modern phones have so much CPU power and the network is relatively slow so compression makes perfect sense. It's quite easy to do also.

On the J2ME side, you do something like this (assuming you use HttpConnection),

  hc.setRequestProperty("Accept-Encoding", "gzip, deflate");
  if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
      InputStream in = hc.openInputStream();
      if ("gzip".equals(hc.getEncoding())) 
         in = new GZIPInputStream(in);
  ...

We use GZIPInputStream from tinyline but I am sure there are others,

http://www.tinyline.com/utils/index.html

On the server side, it's all built-in. Just add following attributes to the Connector in server.xml on Tomcat,

<Connector 
compression="on"
compressionMinSize="2048"
compressableMimeType="text/html,application/json"
... />