delphihttp-status-codestms-web-core

How do I get the status codes for responses on TWebHttpRequest in TMS WEB Core?


I'm using the TWebHttpRequest component in TMS WEB Core to do an API call, but I'm not sure how to get the status codes of the response.

This is the current code that I use to do the API call using the TWebHttpRequest component:

procedure SendEmail(Sender, MailSubject, MailBody, recipients, cc: String);
var
  Email: TWebHttpRequest;
begin
  Email := TWebHttpRequest.Create(nil);

  Email.URL := 'MY_ENDPOINT_URL_FOR_SENDING_EMAIL...';

  Email.Command := httpPOST;
  Email.Headers.Clear;
  Email.Headers.AddPair('Content-Type','application/json');
  Email.PostData := '{' +
    '"Sender": "' + Sender + '",' +
    '"MailSubject": "' + MailSubject + '",' +
    '"MailBody": "' + MailBody + '",' +
    '"recipients": "' + recipients + '",' +
    '"cc": "' + cc + '"' +
  '}';

  Email.Execute(
    procedure(AResponse: string; AReq: TJSXMLHttpRequest)
    begin
      Email.Free;
    end
  );
end;

What I need is the status and/or error codes on the response (200=ok, 403=forbidden, 404=not_found, etc.)

How can I get the status codes when using TWebHttpRequest?


Solution

  • I found this post explaining how to get status codes and they're saying this way:

    procedure TForm1.WebHttpRequest1RequestResponse(Sender: TObject;
      ARequest: TJSXMLHttpRequestRecord; AResponse: string);
    begin
      if (ARequest.req.Status = '404') then
         ...
      if (ARequest.req.Status = '200') then
         ...
    end;
    

    But that wasn't useful to me as I wanted the status codes within the Execute procedure. So I ended up finding out that you can get the status codes through the AReq: TJSXMLHttpRequest parameter as well.

    Email.Execute(
      procedure(AResponse: string; AReq: TJSXMLHttpRequest)
      begin
        console.log('Status: ' + AReq.Status.ToString);
        console.log('StatusText: ' + AReq.StatusText);
      end
    );