gpt4 book ai didi

delphi - 使用 Indy 组件(Delphi XE6)在 Post 上添加 Cookie?

转载 作者:可可西里 更新时间:2023-11-01 17:02:16 28 4
gpt4 key购买 nike

我有一个以表单形式附加到 IdHTTP 组件的 cookiesmanager。

var
XMLRqst : string;
XMLResponse : TStringStream;
XMLRequest : TStringStream;
...
begin
...
IdHTTP1.CookieManager.CookieCollection.Add;
IdHTTP1.CookieManager.CookieCollection[ IdHTTP1.CookieManager.CookieCollection.Count -1 ].CookieName := 'data';
IdHTTP1.CookieManager.CookieCollection[ IdHTTP1.CookieManager.CookieCollection.Count -1 ].Value := '<root user="yyy" company="xxxx">';
IdHTTP1.CookieManager.CookieCollection[ IdHTTP1.CookieManager.CookieCollection.Count -1 ].Path := '/';

...
XMLRequest := TStringStream.Create( XMLRqst, TEncoding.Unicode );
...
idHTTP1.Post( 'http://mysite/api', XMLRequest, XMLResponse );
idHTTP1.Disconnect;

我从未收到“数据”cookie。

  • 如何在 Delphi XE6 中通过 Indy 的 IdHTTP 组件使用 http post 正确发送 cookie?

最佳答案

这是一些工作代码:

procedure SendACookie;
var
HTTP: TIdHTTP;
URI: TIdURI;
ASource: TStringStream;
begin
HTTP := TIdHTTP.Create;
try
HTTP.CookieManager := TIdCookieManager.Create(HTTP);

URI := TIdURI.Create('http://localhost');
try
HTTP.CookieManager.AddServerCookie('habari=mycookievalue', URI);
finally
URI.Free;
end;

ASource := TStringStream.Create('');
try
WriteLn('POST response:');
WriteLn(HTTP.Post('http://localhost/cookies/', ASource));
finally
ASource.Free;
end;
finally
HTTP.Free;
end;
end;

服务器端(使用基于 Indy 的 HTTP 框架):

procedure TShowCookiesResource.OnPost(Request: TIdHTTPRequestInfo; Response: TIdHTTPResponseInfo);
var
I: Integer;
Cookie: TIdCookie;
HTML: string;
begin
HTML := '<html>' + #13#10;

HTML := HTML + Format('<p>%d cookies found:</p>' + #13#10, [Request.Cookies.Count]);

for I := 0 to Request.Cookies.Count - 1 do
begin
Cookie := Request.Cookies[I];
HTML := HTML + Format('<p>%s</p>' + #13#10,
[Cookie.CookieName + ': ' + Cookie.Value]);
end;

HTML := HTML + '</html>';

Response.ContentText := HTML;
Response.ContentType := 'text/html';
Response.CharSet := 'utf-8';
end;

输出:

    Hit any key to send a cookie.    POST response:    1 cookies found:    habari: mycookievalue

长话短说

使用 TIdHTTP.CookieManager.AddServerCookie 方法将 cookie 添加到应随请求一起发送的 IdHTTP 实例。

关于delphi - 使用 Indy 组件(Delphi XE6)在 Post 上添加 Cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24530599/

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