4

如何将 cookie 保存TIdCookieManager到文件中以便以后使用?像浏览器cookies。

4

1 回答 1

9

TIdCookieManager对在文件中持久化 cookie 数据没有任何本机支持。您必须手动实现。使用该TIdCookieManager.CookieCollection属性访问 cookie 对象的列表。例如:

uses
  ..., IdCookie, IdCookieManager;

var
  Cookies: TIdCookieList;
  Cookie: TIdCookie;
  I: Integer;
begin
  Cookies := IdCookieManager.CookieCollection.LockCookieList(caRead);
  try
    for I := 0 to Cookies.Count-1 do
    begin
      Cookie := Cookies[I];
      // save Cookie properties as needed...
    end;
  finally
    IdCookieManager.CookieCollection.UnlockCookieList(caRead);
  end;
end;

.

uses
  ..., IdCookie, IdCookieManager;

var
  Cookies: TIdCookies;
  Cookie: TIdCookie;
begin
  Cookies := IdCookieManager.CookieCollection.LockCookieList(caReadWrite);
  try
    for (each saved cookie) do
    begin
      Cookie := IdCookieManager.CookieCollection.Add;
      try
        // read Cookie properties as needed...
        Cookies.Add(Cookie);
      except
        Cookie.Free;
        raise;
      end;
    end;
  finally
    IdCookieManager.CookieCollection.UnlockCookieList(caReadWrite);
  end;
end;

或者:

uses
  ..., IdCookie, IdCookieManager;

var
  Cookies: TIdCookieList;
  Cookie: TIdCookie;
  I: Integer;
  S: string;
begin
  Cookies := IdCookieManager.CookieCollection.LockCookieList(caRead);
  try
    for I := 0 to Cookies.Count-1 do
    begin
      Cookie := Cookies[I];
      S := Cookie.ServerCookie;
      // save S as needed...
    end;
  finally
    IdCookieManager.CookieCollection.UnlockCookieList(caRead);
  end;
end;

.

uses
  ..., IdCookie, IdCookieManager, IdURI;

var
  S: string;
  Cookies: TIdCookies;
  Cookie: TIdCookie;
  Uri: TIdURI;
begin
  Cookies := IdCookieManager.CookieCollection.LockCookieList(caReadWrite);
  try
    for (each saved cookie) do
    begin
      // read S as needed
      S := ...;
      Uri := TIdURI.Create(URL where cookie came from);
      try
        Cookie := IdCookieManager.CookieCollection.Add;
        try
          Cookie.ParseServerCookie(S, Uri);
          Cookies.Add(Cookie);
        except
          Cookie.Free;
          raise;
        end;
    finally
      Uri.Free;
    end;
  finally
    IdCookieManager.CookieCollection.UnlockCookieList(caReadWrite);
  end;
end;
于 2013-01-17T18:24:42.737 回答