Secure Your REST Client With SSL And GZIP Compression In Delphi XE8 Firemonkey On Android And IOS
Admin
In Delphi XE8 Firemonkey the TRESTClient component is now backed by TNetHTTPClient which uses the native HTTP client on each platform (for example on IOS it uses NSURLConnection). This means that you no longer have to distribute OpenSSL libraries with your Delphi XE8 applications and you will be able to support SSL and GZIP. It should also support Deflate compression. When the native platform updates it’s SSL functionality you automatically take advantage of those updates as well. Under Delphi XE7 using GZIP was also possible. You want to use SSL to secure your application data and GZIP to reduce the size of your downloads especially on a mobile connection. This is especially important if you are building an enterprise app. Your web server must have GZIP enabled for the client to be able to use it. What I found with the new TNetHTTPClient component is that on IOS and Mac OSX the native NSURLConnection component automatically decompresses the content but on Windows and Android the content is still GZIPed. I am including a demo app for Android, IOS32, IOS64, Win32, Win64, and Mac OSX which contains a DecodeGZIPContent() function that utilizes TIdCompressorZlib.DecompressGzipStream depending on the platform where it is needed. Once you set the TRESTRequest.AcceptEncoding to ‘gzip, deflate’ the web server will know your client can accept GZIPed content and should send it to you. You should be able to use this demo with Appmethod as well. Here is the DecodeGZIPContent function from the demo: function TForm1.DecodeGZIPContent(RawBytes: System.TArray<System.Byte>; ContentEncoding: String): String;
var
MSI: TMemoryStream;
MSO: TStringStream;
{$IF NOT DEFINED(MACOS)}
{$ELSE}
I: LongInt;
W: Word;
{$ENDIF}
begin
MSI := TMemoryStream.Create;
MSO := TStringStream.Create;
MSI.WriteData(RawBytes, Length(RawBytes));
{$IF NOT DEFINED(MACOS)}
MSI.Seek(0, 0);
{$ELSE}
MSI.Seek(I, W);
{$ENDIF}
try
{$IF NOT DEFINED(MACOS)}
// Zlib is a TIdCompressorZlib
if ContentEncoding = 'gzip' then
Zlib.DecompressGZipStream(MSI, MSO);
if ContentEncoding = 'deflate' then
Zlib.DecompressHTTPDeflate(MSI, MSO);
{$ENDIF}
except
on e: Exception do
begin
showmessage(e.Message);