Try Except/Finally statements are the things I rarely use and haven't mastered.
Below is the code I used to fetch a web page, here is how it works:
- It uses TFPHTTPClieant to download a page
- The function's result is a string, so I can do some processing further
- If the server provides gzip data, save it to a temp file and uncompress it using TGZFileStream
The function it is working good. But I know it should use some try except and finally blocks. Where should I put them?
Extra question. I searched the web but failed to find code for direct uncompressing gzip stream. Do you know any better code for uncompressing gzip stream from web (without saving it to a temp file)?
function FetchPage: string;
const
URL = 'http://example.com/';
TmpFile = 'downloaded.tmp';
var
Decompressor: TGZFileStream;
strStream: TStringStream;
begin
with TFPHTTPClient.Create(nil) do
begin
AddHeader('User-Agent', 'Mozilla/5.0 (compatible; fpweb)');
AddHeader('Accept-Encoding', 'gzip');
strStream := TStringStream.Create;
Get(URL, strStream);
if ResponseHeaders.Values['Content-Encoding'].Trim = 'gzip' then
begin
strStream.SaveToFile(TmpFile);
strStream.Clear;
Decompressor := TGZFileStream.create(TmpFile, gzopenread);
strStream.CopyFrom(Decompressor, 0);
Decompressor.Free;
end;
Result := strStream.DataString;
strStream.Free;
Free;
end;
// ShowMessage(Result);
end;