Compressing POST Requests in Flutter

Posting to REST endpoints from mobile applications is a very common use case. Some of those POST requests can get a little large and it can be useful to compress them before sending to save the user some data. It turns out to be very easy to do this compression in Flutter and I didn’t find resources for it when I went looking so I thought I’d record the steps I took.

Code Example

void sendCompressed() async {
var gzip = GZipCodec();

  String jsonToSend = '{"field1":"Some JSON to send to the server."}';
  var compressedBody = gzip.encode(jsonToSend.codeUnits);
  Map<String, String> headers = { 
    "Content-Encoding": "gzip", 
    "Content-Type": "application/json; charset=UTF-8",
  };
  var response = await http.post( 
    "https://example.com/api/v1", 
    headers,     
    compressedBody );
}

This is pretty much just the standard example of using POST. The two things that need to change to send compressed content is to add the Content-Encoding header that specifies gzip as the encoding method, and compress the content. Since Dart has support for gzip as one of its standard codecs the compression is simple. In the example above it is done in one line by the gzip.encode method. The http.post method already takes a dynamic argument, which makes it convenient to send the compressed bytes.

Server Side Handling

You will need to check that the server you’re sending to handles compressed content. The app I was building was using API Gateway for the endpoint and that automatically uncompresses the body before passing it on to a Lambda or other internal handler. If there is no automatic handling for compression then you might have to check the header and manually decode the received body.

Leave a Reply

Your email address will not be published. Required fields are marked *