[fpc-devel] Avoid exception if FPHTTPClient cannot connect to server?
Werner Pamler
werner.pamler at freenet.de
Mon Jul 31 13:52:40 CEST 2017
Here is a little demo program which uses fphttpclient to download some
file from some server.
If the URL exists everything is fine (note on Windows, that the OpenSSL
dlls must be copied to the exe directory for the demo to work). If the
URL does not exist, but the server responds, the program returns the
well-known error 404 (if the 404 has been added to the response codes in
HTTPMethod) - also fine. But if a connection to the server cannot be
established -- maybe because the server URL is wrong -- then the program
creates an exception. Synapse, on the other hand, does not crash on this
occasion, it just returns an error 500. This behavior appears to be much
more consistent than fpc's.
Is this intentional? Or should I report a bug?
// ------------------ snip ----------------------
program project1;
{$mode objfpc}{$H+}
uses
Sysutils, Classes, fphttpclient;
function DownloadURL(URL: String; AStream: TStream; out AErrMsg:
String): Boolean;
begin
AErrMsg := '';
with TFPHTTPClient.Create(nil) do
try
AllowRedirect := true;
HTTPMethod('GET', URL, AStream, [200, 404{, 500}]);
Result := (ResponseStatusCode = 200);
if not Result then
AErrMsg := 'Error code ' + IntToStr(ResponseStatusCode) + ': '
+ ResponseStatusText;
finally
Free;
end;
end;
const
// existing URL --> ok
//URL =
'https://sourceforge.net/projects/freepascal/files/Documentation/3.0.2/doc-txt.zip/download';
// Existing server, but not existing URL --> error 404
//URL =
'https://sourceforge.net/projects/freepascal/files/Documentation/3.0.2/doc-txt.zip/download-1';
// Non-existing server
URL =
'https://sourceforge-1.net/projects/freepascal/files/Documentation/3.0.2/doc-txt.zip/download-1';
var
stream: TStream;
errmsg: String;
begin
stream := TFileStream.Create('test.zip', fmCreate);
try
if DownloadURL(URL, stream, errmsg) then
WriteLn('Download of ' + URL + ' completed.')
else
WriteLn(errmsg);
finally
stream.Free;
end;
{$IFDEF WINDOWS}
WriteLn('Press ENTER to quit.');
ReadLn;
{$ENDIF}
end.
More information about the fpc-devel
mailing list