【问题标题】:Delphi XE Indy connects to local server api but not public server apiDelphi XE Indy 连接到本地服务器 api 但不连接公共服务器 api
【发布时间】:2017-01-27 05:01:32
【问题描述】:

我在使用 Delphi XE 通过 Indy Client 连接到公共域 api 时遇到问题。

我可以成功连接到我的本地主机 Web 服务器 api (apache),但是在共享主机上对远程服务器(公共域)的类似尝试给了我一个禁止的 403 错误。

我可以使用 cURL 成功访问相同的公共域 api。因此,我排除了共享托管服务器上的权限/防火墙的任何问题。

    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;

在调用公共 api 之前我需要设置/调整 TIdHTTP Indy 组件的属性/设置吗?

【问题讨论】:

  • 你的 cURL 代码是什么样的? 403 表示您无权访问该 URL,它可能需要您没有提供给 TIdHTTP 的身份验证凭据。你给 cURL 了吗?顺便说一句,utf-8 不是有效的Request.ContentEncoding 值。如果有的话,您应该改用Request.Charset(您不需要为application/json 指定字符集)。
  • 嘿雷米。我发现问题出在组件的 UserAgent 属性上。好像被宿主屏蔽了。

标签: delphi-xe indy


【解决方案1】:

经过大量研究,我在 Indy 知识库中找到了解决问题的方法。

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

我将我的 indy 组件的 UserAgent 属性从默认值更改为

Mozilla/3.0(兼容;Indy 库)

它有效!。

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2020-05-25
    • 2021-11-11
    • 1970-01-01
    • 2017-04-20
    • 2023-03-24
    • 2017-10-07
    • 1970-01-01
    相关资源
    最近更新 更多