Decompressing the TRESTResponse

RAD Studio, Delphi and C++ 10 Seattle has a fantastic REST Client Library. If you are unfamiliar with it, check out my 5 Minute REST Client video.

The TRESTRequest component has an AcceptEncoding property where you can specify the type of compression you would like applied to the response. The TRESTResponse component has a ContentEncoding property that specifies the the encoding that the server chose. The most common compression encoding is gzip, followed by deflate. The others are rarely used (although brotli is a new compression that looks promising for the future.)

By default it is not encrypted if you leave AcceptEncoding blank. However when you use the Stack Overflow API it always compresses with gzip if nothing is specified.

The TRESTResponse has two ways to access the response data directly, the RawBytes property and the Content property. Both are read-only. So we can read the compressed response data, but cannot update the TRESTResponse with the decompressed data. Updating the TRESTReponse allows it to work with the TRESTResponseDataSetAdapter, which is a fantastic feature.

Luckily we can use the protected mode workaround to update the value. Here is a unit that you can include in your project to easily decompress the TRESTResponse and continue to use it with the Data Set Adapter.

unit RestDecompress;

interface

uses
  System.SysUtils, System.Types, System.Classes, IPPeerClient, REST.Client;

procedure DecodeRestResponse(ARestResponse: TRESTResponse);

implementation

uses
  System.Zlib,
  IdBaseComponent, IdException, IdZLibCompressorBase, IdCompressorZLib;

  type // protected mode work around
  TProtectedRESTResponse = class(TRESTResponse)
  end;


procedure DecodeRestResponse(ARestResponse: TRESTResponse);
var
  LCompressed: TMemoryStream;
  LDecompressed: TStringStream;
  LDecompress: TIdCompressorZLib;
begin
  if Length(ARestResponse.ContentEncoding) = 0 then exit;

  LCompressed := nil;
  LDecompressed := nil;
  LDecompress := nil;
  try
    LCompressed := TMemoryStream.Create;
    LDecompressed := TStringStream.Create;

    LCompressed.WriteData(ARESTResponse.RawBytes, Length(ARESTResponse.RawBytes));
    LCompressed.Position := 0;

    // Use the Indy decompression libraries because the HTTP stream doesn't
    //   have the proper headers that System.ZLib looks for.

    LDecompress :=TIdCompressorZLib.Create();

    if ARestResponse.ContentEncoding = 'gzip' then
      LDecompress.DecompressGZipStream(LCompressed, LDecompressed)
    else if ARestResponse.ContentEncoding = 'deflate' then
    begin
      // Due to variations in the deflate server side implementations,
      //   this rarely works, but is here for completeness and just in case
      LDecompress.DecompressHTTPDeflate(LCompressed, LDecompressed);
    end;

    TProtectedRESTResponse(ARESTResponse).SetContent(LDecompressed.DataString);
  finally
    LDecompressed.Free;
    LCompressed.Free;
    LDecompress.Free;
  end;
end;

end.

Simply use this unit, and then add a call to DecodeRestResponse(RESTResponse) to RESTResponse’s OnAfterExecute event handler. It checks the ContentEncoding and then uses the correct decompression and updates the content.

You’ll notice it uses the Indy TIdCompressorZLib component instead of the new System.ZLib library. The reason is a GZip encoded HTTP response doesn’t include the full headers expected by the ZLib library. There is a way to work around this, but no need to do that since the Indy library works fine.

This entry was posted in REST and tagged , , , , , , . Bookmark the permalink.

2 Responses to Decompressing the TRESTResponse

  1. Thanks a lot. I recently started getting into the Delphi Rest Library and stumbled upon this. Very helpful, indeed.

  2. Joseph G. Mitzen says:

    What are you comparing it to when you declare it to be a fantastic REST library? It’s lacking a great deal of features found in other languages’ REST libraries and the API is verbose like TDataset….

    RESTClient.BaseURL := ‘https://accounts.google.com/’;

    RESTRequest.Method := TRESTRequestMethod.rmPOST;
    RESTRequest.Resource := ‘o/oauth2/token’;
    RESTRequest.Params.AddItem(‘code’, edt_GoogleTasks_AuthCode.Text, TRESTRequestParameterKind.pkGETorPOST);
    RESTRequest.Params.AddItem(‘client_id’, edt_GoogleTasks_ClientID.Text, TRESTRequestParameterKind.pkGETorPOST);
    RESTRequest.Params.AddItem(‘client_secret’, edt_GoogleTasks_ClientSecret.Text, TRESTRequestParameterKind.pkGETorPOST);
    RESTRequest.Params.AddItem(‘redirect_uri’, ‘urn:ietf:wg:oauth:2.0:oob’, TRESTRequestParameterKind.pkGETorPOST);
    RESTRequest.Params.AddItem(‘grant_type’, ‘authorization_code’, TRESTRequestParameterKind.pkGETorPOST);

    RESTRequest.Execute;

    It’s easier to build the string yourself and do the whole thing manually than it is to type all of this! And what user who hasn’t used it in 6 months is ever going to remember “TRESTRequestParameterKind.pkGETorPOST”?

    And that’s before we get into the lack of features such as keep-alive and connection pooling, etc. Compression/decompression should be transparent (as they are in other REST libraries) and this kind of manual handling shouldn’t even be necessary. 🙁

Leave a Reply