我有一个表单中附加到IdHTTP组件的cookiemanager。
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;
我从未收到&#34;数据&#34; cookie中。
答案 0 :(得分:3)
以下是一些有效的代码:
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
TL; DR
使用TIdHTTP.CookieManager.AddServerCookie
方法将cookie添加到IdHTTP实例中,该实例应与请求一起发送。