You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Indy TIdHTTP发送POST请求时丢失服务器Cookie问题排查

我使用Indy 10.6.2.5366和Delphi Tokyo 10.2 update3开发应用,遇到以下问题:

  • 发送HTTPS POST请求后,TIdHTTP的CookieManager中没有任何Cookie,但用Postman执行完全相同的请求时,响应里存在名为ROUTEID的Cookie:
    Postman请求
  • 但在Delphi中执行相同请求,却无法获取到ROUTEID Cookie:
    Delphi请求截图
  • Postman显示响应包含10个头部,而Delphi的TIdHTTP.Response.RawHeaders中仅能看到8个。
  • 请求返回的响应码是401未授权,但即使是这个错误响应,Postman仍能拿到Cookie,Delphi却不行。

这些Cookie包含后续请求所需的认证信息,必须持久化。之前看到Remy Lebeau提到TCookieManager已完全重写,但我肯定哪里操作有误。

以下是我的代码:

procedure TestMethod(AUrl, ABody: string);
var
  HTTP: TIdHTTP;
  SSL: TIdSSLIOHandlerSocketOpenSSL;
  LStreamRequestBody: TStringStream;
  LReturnBody: string;
  LCookieList: TIdCookieList;
  n: Integer;
begin

  HTTP := TIdHTTP.Create(nil);
  SSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  LStreamRequestBody := TStringStream.Create(ABody, TEncoding.UTF8);
  try
    IdOpenSSLSetLibPath(Utils.Global.SSLLibPath);

    SSL.SSLOptions.Method := sslvSSLv23;
    SSL.SSLOptions.SSLVersions := [sslvTLSv1_2, sslvTLSv1_1, sslvTLSv1];
    SSL.SSLOptions.Method := sslvSSLv23;

    HTTP.IOHandler := SSL;
    HTTP.Response.ContentType := 'application/json;charset=utf-8';
    HTTP.Request.CustomHeaders.FoldLines := True;
    HTTP.Request.Accept := '*/*';
    HTTP.Request.ContentType := 'application/json';
    HTTP.Request.Connection := 'keep-alive';
    HTTP.Request.AcceptEncoding := 'gzip, deflate, br';
    HTTP.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0';

    HTTP.CookieManager := TIdCookieManager.Create(nil);
    HTTP.AllowCookies := True;
    HTTP.HandleRedirects := True;

    try
      LReturnBody := HTTP.Post(AUrl, LStreamRequestBody);
    Except
      on e: EIdHTTPProtocolException do
      begin
        LCookieList := HTTP.CookieManager.CookieCollection.LockCookieList(caRead);
        try
          for n := 0 to LCookieList.Count - 1 do
          begin

          end;
        finally
          HTTP.CookieManager.CookieCollection.UnlockCookieList(caRead);
        end;
      end;
    end;
  finally
    LStreamRequestBody.Free;
    HTTP.Free;
    SSL.Free;
  end;
end;

内容的提问来源于stack exchange,提问作者Rebelss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:10:05