delphi - 将 TIDCookieManager 中的 Cookie 保存到文件中

标签 delphi delphi-xe2 indy indy10 delphi-xe3

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

最佳答案

TIdCookieManager 没有任何对在文件中保存 cookie 数据的 native 支持。您必须手动实现。使用 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;

关于delphi - 将 TIDCookieManager 中的 Cookie 保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14382732/

相关文章:

delphi - 虚拟字符串树中节点/行中的多个复选框/单选按钮

delphi - Delphi 中通过引用传递 const

delphi - 使用 Delphi 进行条码扫描

delphi - 无法从 delphi 中的 TIdHTTP 连接到 TIdHTTPServer

delphi - 为什么 TIdTextEncoding.Default 未声明?

Delphi TeeChart - 打印预览和保存对话框

delphi - 将客户端应用程序迁移到 FB 2.1

delphi - 使用 SSL 连接时出错

delphi - 将我的显示器设置为 dll 中的任务时出现错误 "Task can be only monitored with a single monitor"

arrays - 如何在没有 ShareMem 单元的情况下将动态字符串数组传递给 dll 库(dll 和用 d7 编写的客户端)?