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.
HTTP compression allows content to be compressed on the server before transmission to the client. For resources such as text this can significantly reduce the size of the response message, leading to reduced bandwidth requirements and download times.
Gzip is a file format and software application used on Unix and Unix-like systems to compress HTTP content before it's served to a client.
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"
... />
You can compress the content of an HTTP request or response, but not the headers. See section 3.6 of the HTTP 1.1 spec, and the later section that describes the Content-Encoding header.
EDIT: The flip side of this is that there is no guarantee that an HTTP server side will accept any particular compression format. And depending on the quality of the server-side implementation of HTTP, it might not even recognize that the request content has been compressed. So you don't want to do this unless you know that the server-side supports compressed request content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With