Error handling in fphttpclient?

2k views Asked by At

fphttpclient works fine with simple examples like

procedure ReadFromURL(theURL: string);
var
  httpClient: TFPHTTPClient;
  FileContents: String;
  theStatusCode: integer; 
begin
  httpClient := TFPHTTPClient.Create(nil);
  try
    FileContents := httpClient.Get(theURL);
    theStatusCode := httpClient.ResponseStatusCode;
    if theStatusCode = 200 then
     begin
       ; // do something
     end
    else
     ShowMessage(IntToStr(theStatusCode));
  finally
    httpClient.Free;
  end;
end;

but only, if the URL exists, so that the status code is 200. In other cases the code crashes at httpClient.Get with an exception of class EHTTPClient, ESocketError or EXC_BAD_ACCESS, although the procedure uses a try ... finally section (formulating it as try ... except doesn't change anything). Unfortunately, the exception is raised before the status code can be processed.

What is the recommended way to handle errors with fphttpclient? Is there any method to check for the existence of a resource (and, possibly, the correctness of an URL, too), before invoking the Get method?

1

There are 1 answers

0
Marco van de Voort On BEST ANSWER

Make sure the various events are assigned, so that the class knows what to do on password prompts, redirects etc.

Standard examples init the class like

With TFPHTTPClient.Create(Nil) do
  try
    AllowRedirect:=True;
    OnRedirect:=@ShowRedirect;
    OnPassword:=@DoPassword;
    OnDataReceived:=@DoProgress;
    OnHeaders:=@DoHeaders;
    { Set this if you want to try a proxy.
    Proxy.Host:='ahostname.net.domain';
    Proxy.Port:=80;

etc.

Please study examples and try to sort through your problems till you have reproducible cases. If then there is still a problem, please submit it to the bugtracker

In rare cases, checking the existences of headers with HEAD() can speed up e.g. sifting through lists of old urls