Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - Can I compress HTTP Requests using GZIP?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"
... />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...