0

I am using a TNetHTTPClient in a Delphi 10.2.3 Firemonkey project and would like to clear all stored cookies. I did not find any solution in the help files. I tried this code, but I get the error that the array is read-only:

SetLength(NetHTTPClient1.CookieManager.Cookies, 0);

What can I do to clear all cookies, without destroying the instance of TNetHTTPClient and creating it again?

Flo
  • 219
  • 2
  • 10

2 Answers2

1

Just an idea:

for i := 0 to High(NetHTTPClient1.CookieManager.Cookies)
  do NetHTTPClient1.CookieManager.Cookies[i].Expires := Now - 1;

NetHTTPClient1.CookieManager.dCookies;

This way you can set all cookies as expired. Getting cookies again call GetCookies that internally call DeleteExpiredCookies

Edit

Unfortunetely this will not work (read comments below for details)

BigBother
  • 367
  • 2
  • 9
  • I really like your idea. Unfortunately, the property "Cookies" is read-only: property Cookies: TCookiesArray read GetCookies; – Flo Apr 26 '18 at 07:37
  • Hi @Flo it doesn't matter, expired cookies are cleared on property read! – BigBother Apr 26 '18 at 11:18
  • Hi BigBother, your statement is absolutely correct. But as the whole array of cookies is read-only, I cannot modify the `Expires` property. Does your code work for you? – Flo Apr 27 '18 at 12:47
  • Hi @Flo, the `Cookies` array is readonly (you cannot assign to it) but its elements (`TCookie` records) are not, you can modify single cookie property `Expires` without any problem (I'm under Delphi 10.2.2, not updated to 10.2.3 yet) – BigBother Apr 28 '18 at 09:52
  • I just tried it again, I cannot change any value of the record. They preserve their original value. – Flo Apr 30 '18 at 09:51
  • @Flo totally my bad, GetCookies returns an array derived from FCookies (which is a TList instead) so you can modify a single cookie, but your edits will be lost... – BigBother Apr 30 '18 at 14:33
  • BigBother, never mind. Your idea was helpful, anyway. – Flo May 02 '18 at 09:04
0

I figured it out, many thanks to BigBother and Toon Krijthe in another thread about class helpers!

As CookieManager.Cookies is read-only, I tried to gain access to the private field TCookies via a class helper, which does not work anymore since 10.1 Berlin. However, Toon Krijthe found a way, and I adapted it to suit my needs:

Interface:

type
  TCookieManagerHelper = class helper for TCookieManager
    procedure DeleteCookies;
  end;

Implementation:

procedure TCookieManagerHelper.DeleteCookies;
begin
  with self do
    FCookies.clear;
end;

Whenever I want to clear cookies:

NetHTTPClient1.CookieManager.DeleteCookies;

I have to add that this might not work with future versions of Delphi, as Embarcadero disabled accessing private fields via class helpers on purpose.

Flo
  • 219
  • 2
  • 10