当前位置: 开源爱好者 » 编程教程 » Delphi教程 » 正文

Delphi 使用IdHttp获取Cookie操作

Delphi 使用IdHttp获取Cookie操作,用一个登录程序获取请求返回的数据,判断是否有特定名称的cookie:

var
  i: Integer;
  tmp, cookie: String;
  IdHTTP1: TIdHTTP;
  postStrings: TStringList;
  tempstr    : WideString;
begin
  postStrings := TStringList.Create;
  postStrings.Append('参数名=' + '参数值字符串');//传递参数 
  IdHTTP1 := TIdHTTP.Create(nil);
  IdHTTP1.AllowCookies := True;
  //获取请求返回的数据
  tempstr :=  IdHTTP1.Post('http://e.baidu.com/mpos/common/login', postStrings);      
  cookie := '';
  for i := 0 to IdHTTP1.Response.RawHeaders.Count - 1 do
  begin
    tmp := IdHTTP1.Response.RawHeaders[i];
    if pos('set-cookie:', LowerCase(tmp)) = 0 then Continue;
    tmp := Trim(Copy(tmp, Pos('Set-cookie:', tmp) + Length('Set-cookie:'), Length(tmp)));
    tmp := Trim(Copy(tmp, 0, Pos(';', tmp) - 1));
    if Pos('_t_mpos', tmp) > 0 then  //判读是否有特定名称的Cookie
    begin
      tmp := StringReplace(tmp,'_t_mpos', '', []);
      tmp := StringReplace(tmp,'=', '',  []);
      tmp := StringReplace(tmp,':', '', []);
    end
    else
      Continue;
    cookie := Trim(tmp);
  end;
  IdHTTP1.Disconnect;
  IdHTTP1.Free;

CopyRight 2015© 开源爱好者 All Rights Reserved 豫ICP备16030607号 隐私声明 网站地图