Jump to content
Sign in to follow this  
softtouch

Load and save cookies with System.Net.HttpClient, how?

Recommended Posts

System.Net.HttpClient has a cookiemanager, which holds all the cookies. How can I save them and reload them when the program restart? The cookies array of the cookiemanager is read-only.

Share this post


Link to post

This can't be done due to unfortunate design of TCookieManager class. The class is pretty much sealed for extension, because it lacks virtual methods. The best you can do is to apply nasty hacks or crate a QP ticket.

Share this post


Link to post

Come on! It is not that bad when we use a class helper:

type
  TCookieManagerHelper = class helper for TCookieManager
  private
    function GetCookiesAsString: string;
    procedure SetCookiesAsString(const Value: string);
  public
    property CookiesAsString: string read GetCookiesAsString write SetCookiesAsString;
  end;

function TCookieManagerHelper.GetCookiesAsString: string;
var
  lst: TStringList;
begin
  lst := TStringList.Create();
  try
    for var cookie in Cookies do
      lst.Add(cookie.GetServerCookie);
    Result := lst.CommaText;
  finally
    lst.Free;
  end;
end;

procedure TCookieManagerHelper.SetCookiesAsString(const Value: string);
var
  lst: TStringList;
begin
  lst := TStringList.Create();
  try
    lst.CommaText := Value;
    for var S in lst do begin
      var uri := Default(TURI);
      var cookie := TCookie.Create(S, uri);
      uri.ComposeURI('', '', '', cookie.Domain.Substring(1), 0, cookie.Path, nil, '');
      AddServerCookie(cookie, uri);
    end;
  finally
    lst.Free;
  end;
end;

 

Share this post


Link to post
7 minutes ago, Uwe Raabe said:

It is not that bad when we use a class helper:

From the 1st glance, this could be also done with plain old procedures b/c all used members are public

Share this post


Link to post
30 minutes ago, Fr0sT.Brutal said:

From the 1st glance, this could be also done with plain old procedures b/c all used members are public

Of course, that could be done. IMHO it is just a bit less elegant.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×