Introduction
We’re working on an Android application that will be largely community based, so there’s a lot of information going back and forwards.
Our target phones are extremely low-tech though – Android 2.3 and Edge are the platform we’re aiming at. As a result of all of this, we needed to enable HTTP compression to try and minimize the amount of information we’re pumping over these tiny tubes.
Doing this turned out to be far easier than expected. One filter for Spring and setting a couple of headers in the Android Annotations rest templates was all that was needed.
Spring
We initially started following this tutorial that lays out, fairly neatly, the steps you’d need to follow to add a GZIP filter. This includes creating and setting up the filter, and creating a Servlet Response Wrapper that handles the creation of a response stream that ultimately unzips the data.
Luckily, shortly after starting to follow the tutorial IntelliJ began offering to import the classes that we were about to create – it turns out that identical classes exist in the jetty-util library that we were already using. These worked out perfectly, requiring only that we set them up in our web.xml as so.
1 2 3 4 5 6 7 8 9 |
<filter> <filter-name>gzipFilter</filter-name> <filter-class>org.mortbay.servlet.GzipFilter</filter-class> </filter> <filter-mapping> <filter-name>gzipFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> |
Immediately following this, we could see via our standard browsing that the Accept-Encoding: gzip header was being accepted by our server.
Android Annotations
The Android Annotations side was just as easy. The support for gzip already exists, so all that you need to do is pass through a header to the server indicating that you’re willing to accept it.
We did this via an interceptor on the @Rest annotation.
1 |
@Rest(rootUrl = RestConstants.ROOT_URL, interceptors = {HeadersRequestInterceptor.class}) |
Our interceptor gets the headers off of the HttpRequest and adds the "Accept-Encoding: gzip" header.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; public class HeadersRequestInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().set("Accept-Encoding", "gzip"); return execution.execute(request, body); } } |
Leave a Reply