1

我正在尝试使用 Delphi XE3 和 Indy10 编写一个使用 Mashape API 服务的客户端应用程序,但我遇到了一些障碍。

这是我尝试过的:

我在表单上放置TIdHTTP和组件,并使用该属性TIdSSLIOHandlerSocketOpenSSL将它们链接在一起。TIdHTTP.IOHandler然后我在表单上放置了一个按钮和备忘录,并在按钮OnClick事件上放置了以下代码:

procedure TForm1.Button2Click(Sender: TObject);
begin
 IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL1;
 IdHTTP1.Request.CustomHeaders.AddValue('X-Mashape-Key: ','<my_api_key>');
 Memo1.Lines.Text := IdHTTP1.Get('https://hbrd-v1.p.mashape.com/anime/log-horizon');
end;

然后我启动我的应用程序,当我按下按钮时,应用程序将等待片刻,然后吐出一条HTTP/1.1 403 Forbidden错误消息。第二次按下按钮将产生一条HTTP/1.1 500 Internal Service Error消息。

我已经检查过我的系统上是否有所需的 SSL 库文件,并且确实有,并且我已经一次又一次地测试了我的凭据,它们似乎是正确的,而且我知道 url 是正确的,所以我一定是丢失了我的代码中的某些内容会导致显示这些错误。我希望在这方面有更多经验的人可以提供一些建议。

更新:这是TRESTClient有效的代码:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, Vcl.StdCtrls,
  REST.Response.Adapter, REST.Client, Data.Bind.Components,
  Data.Bind.ObjectScope;

type
  TForm1 = class(TForm)
    RESTClient1: TRESTClient;
    RESTRequest1: TRESTRequest;
    Button1: TButton;
    Memo1: TMemo;
    RESTResponse1: TRESTResponse;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
 RESTClient1.BaseURL := 'https://hbrd-v1.p.mashape.com/anime/log-horizon';
 RESTRequest1.Execute;
 Memo1.Lines.Text := RESTResponse1.Content;

// The only thing not shown here is the RESTRequest1.Params which are
// Name: 'X-Mashape-Key'
// Value: 'my-api-key'
// Kind: pkHTTPHEADER
// Everything else is included here which isn't much.
end;

end.

我想对TIdHTTP.

4

1 回答 1

2

如果不看到来回传递的实际 HTTP 消息,就很难知道实际发生了什么。当 HTTP 响应指示错误时,EIdHTTPProtocolException会引发异常,并且其ErrorMessage属性包含服务器响应的正文。它是否向您说明了错误发生的原因?

但是,您确实需要更改此设置:

IdHTTP1.Request.CustomHeaders.AddValue('X-Mashape-Key: ','<my_api_key>');

对此:

IdHTTP1.Request.CustomHeaders.Values['X-Mashape-Key'] := '<my_api_key>';

并摆脱程序IdHTTP1.IOHandler := IdSSLIOHandlerSocketOpenSSL1;分配,因为您已经在表单设计器中处理了它。

除此之外,403错误意味着服务器不接受您的凭据。我没有看到您为代码中的TIdHTTP.Request.UsernameandTIdHTTP.Request.Password属性分配任何凭据,您是在表单设计器中这样做的吗?

TIdHTTP使用插件系统处理 HTTP 身份验证方案。如果服务器允许BASIC身份验证,您可以将该TIdHTTP.Request.BasicAuthentication属性设置为 true,以便BASIC在没有其他身份验证方案可用时用作默认值。您可以使用该TIdHTTP.OnSelectAuthorization事件来查看服务器实际支持的身份验证。

如果服务器需要非BASIC身份验证,您需要将相关添加IdAuthentication...到您的uses子句以启用该插件。例如,IdAuthenticationDigest用于DIGEST身份验证、IdAuthenticationNTLM身份NTLM验证等。或者,添加IdAllAuthentications单元以启用所有插件。

如果您需要使用 Indy 不支持的 HTTP 身份验证(OATH例如),您可以:

  1. 用于TIdHTTP.Request.CustomHeaders.Values['Authorization']手动提供相关凭证数据。

  2. 实现一个自定义TIdAuthentication派生类,并将其实例分配给TIdHTTP.Request.Authorization属性,或将其类类型分配给事件的VAuthenticationClass参数TIdHTTP.OnSelectAuthorization

于 2014-07-09T01:09:57.670 回答