0
votes

I am having issues connecting to a public domain api with Indy Client using Delphi XE.

I can connect successfully to my localhost web server api (apache) successfully but a similar attempt to a remote server (public domain) on shared hosting gives me a forbidden 403 error.

I can access the same public domain api using cURL successfully. Therefore I ruled out anything any issues with rights/firewall on the shared hosting server.

    function CallService(ServiceID: string;payload:string): string;
    var
      JsonToSend: TStringStream;
      ServerResponse,EndPointURL: string;
      LastJSONArray: TStringList;
      MyIndy : TIdHTTP;
    begin

     //Local connection WORKS :)
     EndPointURL := 'http://localhost/api/index.php';

     //Remote/Public Domain connection FAILS :(
     EndPointURL := 'http://example.com/api/index.php';

     LastJSONArray := TStringList.Create();

     LastJSONArray.Values['service_id'] := ServiceID;
     LastJSONArray.Values['payload'] := payload;

     JsonToSend := TStringStream.Create(LastJSONArray.Text, TEncoding.UTF8);

      MyIndy := TIdHTTP.Create;

      try

        try

          MyIndy.Request.Accept := 'application/json';
          MyIndy.Request.ContentType := 'application/json';
          MyIndy.Request.ContentEncoding := 'utf-8';        

          ServerResponse := MyIndy.Post(EndPointURL, JsonToSend);

          Result := ServerResponse;

         except
          on E: EIdHTTPProtocolException do
           //status := http.ResponseText;
           //code := E.ErrorCode;
           if E.ErrorCode = 401 then ShowMessage('You are not authorised!')
           else ShowMessage('Poor Connection '+E.Message);

          on E: Exception do begin
            //do something else
            ShowMessage('Poor Connection - B');
          end;

        end;

      finally
        MyIndy.Free();
        JsonToSend.Free();
        LastJSONArray.Free();
      end;

    end;

Is there property/setting with the TIdHTTP Indy component that i need to set/adjust before calling the public api?

1
What does your cURL code look like? 403 means you don't have access to the URL, it probably requires authentication credentials that you are not giving to TIdHTTP. Are you giving any to cURL? BTW, utf-8 is not a valid Request.ContentEncoding value. You should be using Request.Charset instead, if at all (you don't need to specify a charset for application/json). - Remy Lebeau
Hey Remy. I found the issue was with the UserAgent property of the component. Seems it was being blocked by the host. - davykiash

1 Answers

1
votes

After quite some research I found a solution to my problem on the Indy Knowledge Base.

http://www.indyproject.org/KB/iamgettinga403forbiddene.htm

I changed the UserAgent property of my indy component from the default

Mozilla/3.0 (compatible; Indy Library)

and it works!.