我需要在 FireMonkey 中实现一个 REST API 来获取一些信息,但我不确定该怎么做。
REST API 使用 OAuth2,我可以访问两个代码:Consumer Key 和 Consumer Secret。在此之后,我需要获得一个临时的 Bearer token 。
要请求临时 token ,需要对 token 端点执行 HTTP POST 请求 https://apigateway.serpro.gov.br/token , 在 HTTP 中通知访问凭证 (consumerKey: consumerSecret)
Authorization
Header,base64格式,如下图。
[POST] grant_type = client_credentials
[HEAD] Authorization: Basic Base64 (Consumer key: ConsumerSecret)
如何使用 Delphi 获取访问 token ?
最佳答案
当身份验证方法为 client_credentials 时,Delphi REST Framework 附带的 OAuth2 组件很遗憾无法工作,因此您必须手动进行。 我已经包含了我用来了解它是如何工作的测试代码。甚至今天再次测试它以确保它有效:)
在窗体上放置一个备忘录和一个按钮,并设置 Button1 的 OnClick 事件,将
您也可以使用 Firemonkey 访问 REST 组件,所以这只是为了展示 REST 框架。
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
GaToken: string;
GaTokenType: string;
GaTokenExpire: integer;
end;
var
Form1: TForm1;
implementation
uses
REST.Types,
REST.Client,
REST.Utils,
System.NetEncoding,
System.Net.HttpClient;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
vClientId,
vClientSecret,
vScope,
aExpire: string;
LClient: TRESTClient;
LRequest: TRESTRequest;
LResponse: TRESTResponse;
begin
// Scope is not mandatory and can be skiped
vClientId := '<your_clientID>';
vClientSecret := '<your_seecret>';
// vScope := '<Your_scope>;
LClient := TRESTClient.Create('<YOUR_TOKEN_URL>');
try
LRequest := TRESTRequest.Create(LClient);
try
LResponse := TRESTResponse.Create(LClient);
try
LRequest.Client := LClient; // This line is not really needed but it is good for code readability, see TRESTRequest.Create(LClient);
LRequest.Response := LResponse;
LRequest.Method := rmPOST;
LRequest.AddAuthParameter('grant_type', 'client_credentials', pkGETorPOST);
LRequest.AddAuthParameter('client_id', vClientId, pkGETorPOST);
LRequest.AddAuthParameter('client_secret', vClientSecret, pkGETorPOST);
// LRequest.AddAuthParameter('scope', vScope, pkGETorPOST);
LRequest.Execute;
LResponse.GetSimpleValue('access_token', GaToken);
LResponse.GetSimpleValue('token_type', GaTokenType);
LResponse.GetSimpleValue('expires_in', aExpire);
GaTokenExpire := aExpire.ToInteger;
Memo1.Clear;
Memo1.Lines.Add(IntToStr(LResponse.StatusCode) + ' / ' + LResponse.StatusText);
Memo1.Lines.Add('------------ R A W R E S P O N S E ---------------------');
Memo1.Lines.Add(LResponse.Headers.Text);
Memo1.Lines.Add('--------------------------------------------------------------');
Memo1.Lines.Add(LResponse.Content);
Memo1.Lines.Add('-------------------- T O K E N -----------------------------');
Memo1.Lines.Add(GAToken);
finally
LResponse.Free;
end;
finally
LRequest.Free;
end;
finally
LClient.Free;
end;
end;
end.
关于rest - 如何在 FireMonkey 中使用 REST API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64825398/