Delphi Indy http.get with curl returns: 未经授权

Delphi Indy http.get with curl returns: unauthorized

根据供应商数据我应该有:

我已将其翻译成 Delphi(Indy TidHttp):

procedure TForm42.Button2Click(Sender: TObject);
var
  resp: TMemoryStream;
begin
  resp := TMemoryStream.Create;
  try
    IdHTTP1.Request.Clear;
    IdHTTP1.Request.Accept := 'application/json';
    IdHTTP1.Request.BasicAuthentication := True;
    IdHTTP1.Request.CustomHeaders.FoldLines := False;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + TokenStr;
    IdHTTP1.Get('http://10.10.1.62:8080/api/v1/doors', resp);
    resp.Position := 0;
    memCall.Lines.LoadFromStream(resp);
  finally
    resp.Free;
  end;
end;

我在这里读了很多,所以最后我还添加了'折叠线() 我也试过 'X-Authorization' 作为参数,这是我从 R. Lebeau 那里读到的,但我得到的唯一反应是错误对话框说“401 未授权”。

我确定令牌字符串 (-> 'bearer ' + TokenStr),因为我在将字符串放入供应商试用版时得到了答案。

有人知道我做错了什么吗?

使用自定义身份验证时,

Request.BasicAuthentication 应该是 False 而不是 True

并且您不需要设置 CustomHeaders.FoldLines,因为 TIdHTTP 已经默认禁用折叠(在 the other question 发布时默认情况下并未禁用)。

否则,其余代码看起来没问题。

不过,我建议在调用 LoadFromStream() 时指定 TEncoding.UTF8),例如:

procedure TForm42.Button2Click(Sender: TObject);
var
  resp: TMemoryStream;
begin
  resp := TMemoryStream.Create;
  try
    IdHTTP1.Request.Clear;
    IdHTTP1.Request.Accept := 'application/json';
    IdHTTP1.Request.BasicAuthentication := False;
    IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + TokenStr;
    IdHTTP1.Get('http://10.10.1.62:8080/api/v1/doors', resp);
    resp.Position := 0;
    memCall.Lines.LoadFromStream(resp, TEncoding.UTF8);
  finally
    resp.Free;
  end;
end;

或者,使用 TIdHTTP.Get() 的重载 returns a string:

procedure TForm42.Button2Click(Sender: TObject);
begin
  IdHTTP1.Request.Clear;
  IdHTTP1.Request.Accept := 'application/json';
  IdHTTP1.Request.BasicAuthentication := False;
  IdHTTP1.Request.CustomHeaders.Values['Authorization'] := 'Bearer ' + TokenStr;
  memCall.Text := IdHTTP1.Get('http://10.10.1.62:8080/api/v1/doors');
end;