TIdHTTP: Check for valid cookies before sending request?
-
02-06-2021 - |
Question
I'm using Indy TIdHTTP
along with TIdCookieManager
. I would like to check the current cookies for the request I'm about to send and identify the likelyhood that it will be valid (I know I can't be 100% sure the server will accept my request). If there are no cookies, or if they're expired, I will want to login first and acquire new cookies. Otherwise, just send the request.
How would I go about doing such a check? I believe I have to check the cookie manager before I send a request, but don't know what to check.
Solution
Try something like this:
function CheckCookies(Cookies: TIdCookieManager; const TargetURL: String): Boolean;
var
URL: TIdURI;
Headers: TIdHeaderList;
begin
Result := False;
URL := TIdURI.Create(TargetURL);
try
Headers := TIdHeaderList.Create(QuoteHTTP);
try
Cookies.GenerateClientCookies(URL, False, Headers);
Result := Headers.Count > 0;
finally
Headers.Free;
end;
finally
URL.Free;
end;
end;
.
if not CheckCookies(IdHTTP1.CookieManager, 'http://www.someurl.com/') then
begin
// login and get new cookies ...
end;
OTHER TIPS
Like already stated in the comments you cannot perform an actual acceptance check on the client, only the server can do that.
However you can filter out expired or invalid cookies:
function filterInvalidCookies(cookies: TIdCookies; targetURL: TIdURI): Boolean;
var
c: Integer;
begin
Result := False;
c := 0;
while (cookies.Count > c) do
if (not cookies[c].IsExpired and cookies[c].IsAllowed(targetURL, False) and
(cookies[c].CookieName <> '')) then
begin
Result := True;
Inc(c);
end
else
cookies.Delete(c);
end;
The function removes invalid cookies and returns False if there are no valid ones left. Call it before a request like this:
if (Assigned(con.CookieManager)) then
filterInvalidCookies(con.CookieManager.CookieCollection,
TIdURI.Create('http://www.someurl.com/'));
where con
is an TIdHTTP
object.
You can do additional, maybe target page specific checks of course.