gpt4 book ai didi

delphi - Google 通讯录 token 过期

转载 作者:行者123 更新时间:2023-12-03 18:35:11 36 4
gpt4 key购买 nike

我与 Google 通讯录合作,一切顺利。但一个小时后,我需要手动刷新授予的访问权限。据此SO question我应该能够通过这个调用更新我的 refresh_token :

refresh_token = requests.post(
'https://accounts.google.com/o/oauth2/token',
data={
'client_id': APP_ID,
'client_secret': APP_SECRET,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
}
)

我已经翻译成这个 Delphi 代码
var
Http: TidHttp;
URLString: string;
Req, Resp: TStringStream;
begin
Http := TidHttp.Create(nil);
try
URLString := 'client_id=' + FGoggleContacts.ClientID;
URLString := URLString + '&client_secret=' + FGoggleContacts.ClientSecret;
URLString := URLString + '&refresh_token=' + FGoggleContacts.RefreshToken;
URLString := URLString + '&grant_type=refresh_token';

Req := TStringStream.Create(URLString);
Resp := TStringStream.Create('');
HTTP.DoRequest(Id_HTTPMethodPost, 'https://accounts.google.com/o/oauth2/token', Req, Resp, []);

finally
Req.Free;
Resp.Free;
Http.Free;
end;
end;

但是当调用它时,我得到一个 http/1.1 400 bad request错误

简而言之,我如何保持与 Google 的联系?

更新

在@mjn42 的帮助下,我发现我错过了 Content-Type在我的要求中。所以我写了一个新方法来刷新我的 token :
procedure TGContacts.RefreshTokens;
var
Http: TidHttp;
URLString: string;
Req, Resp: TStringStream;
JSon: ISuperObject;
begin
Http := TidHttp.Create(nil);
Req := TStringStream.Create('');
Resp := TStringStream.Create('');
try
URLString := 'client_id=' + FClientID;
URLString := URLString + '&client_secret=' + FClientSecret;
URLString := URLString + '&refresh_token=' + FRefreshToken;
URLString := URLString + '&grant_type=refresh_token';
Req.WriteString(URLString);

HTTP.Request.ContentType := 'application/x-www-form-urlencoded';
HTTP.DoRequest(Id_HTTPMethodPost, 'https://accounts.google.com/o/oauth2/token', Req, Resp, []);
if HTTP.ResponseCode = 200 then
begin
JSon := SO(UTF8Decode(Resp.DataString));
FAccessToken := JSon['access_token'].AsString;
if JSon['refresh_token'] <> nil then
FRefreshToken := JSon['refresh_token'].AsString;
end;

finally
Req.Free;
Resp.Free;
Http.Free;
end;
end;

我只是在访问 API 之前调用它,然后 token 不会过期。

最佳答案

根据 https://www.rfc-editor.org/rfc/rfc6749#section-6 上的规范请求应使用 内容类型:application/x-www-form-urlencoded :

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA

关于delphi - Google 通讯录 token 过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42000720/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com