IdHTTP 设置cookie 和访问后读取Cookie 值。

procedure TForm1.btn1Click(Sender: TObject);
var
  IdHTTP: TIdHTTP;
  mstrCookie: string;
  Cookies : TIdCookieManager;
  i: Integer;
begin
  IdHTTP := TIdHTTP.Create(nil);

  IdHTTP.Request.UserAgent := '';
  mstrCookie := 'aaa=5555&bb=12345';
  IdHTTP.Request.AcceptEncoding := '';
  if mstrCookie <> '' then
  begin
    IdHTTP.Request.SetHeaders; //说要加这一句。
    IdHTTP.Request.CustomHeaders.Add('Cookie: ' + mstrCookie); 
  end;

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

  IdHTTP.ReadTimeout := 25000; //设置读取超时
  Memo1.text := IdHTTP.Get('http://www.baidu.com/');

   mstrCookie:='';
  //Memo1.Lines.Add (Cookies.CookieCollection.Items[0].CookieText); 
  for i := 0 to Cookies.CookieCollection.Count - 1 do
  begin
    Memo1.Lines.Add(Cookies.CookieCollection.Items[i].CookieName + 'Value:' + Cookies.CookieCollection.Items[i].Value);
    mstrCookie:=mstrCookie+  Cookies.CookieCollection.Items[i].CookieName+'='+  Cookies.CookieCollection.Items[i].Value +'&';
  end;
    Memo1.Lines.Add ( mstrCookie);

  IdHTTP.free;
end;

你可能感兴趣的:(IdHTTP 设置cookie 和访问后读取Cookie 值。)