根據供應商資料,我應該有:
- Http 型別 GET
- 回應型別:application/json
- 引數:授權:bearer Token
- curl: curl -X GET --header 'Accept: application/json' --header '授權: Bearer Token, 'http://localhost:8080/api/v1/doors'
- 請求網址:'http://localhost:8080/api/v1/doors'
我已將其翻譯為 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;
我在這里讀了很多關于它的內容,所以最后我還添加了“折疊線(向 TIdHttp 請求添加自定義標頭,標頭值有逗號)我還嘗試了“X-Authorization”作為引數,這是我從 R. Lebeau 那里讀到的,但唯一我得到的反應是一個錯誤對話框,上面寫著“401 未授權”。
我確定令牌字串(-> 'bearer' TokenStr),因為我在將字串放入供應商試用版時得到了答案。
有人知道我做錯了什么嗎?
uj5u.com熱心網友回復:
Request.BasicAuthentication使用自定義身份驗證時False不應該這樣做。True
而且您不需要設定CustomHeaders.FoldLines為默認情況下已經禁用折疊(在發布另一個問題TIdHTTP時默認情況下它沒有被禁用)。
否則,其余代碼看起來不錯。
不過,我建議TEncoding.UTF8在呼叫LoadFromStream()) 時指定,例如:
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()that 的多載回傳 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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446161.html
