如何让webbrowser通过idhttp来登录获取了cookie实现自动登录?

现在做一个客户端系统,登录使用的idhttp的pos请求,登录成功后会返回一个cookie,我放了一个IdCookieManager控件关联了idhttp控件,客户端系统内部写了个内置浏览器,动态创建webbrowser打开网页,现在需要用之前获取的cookie来实现网页系统的自动登录,自己测试过一些网上常见的方法
1、
doc := wb1.Document as IHTMLDocument2;
doc.cookie := cookie;
wb1.Refresh;
这种方式不知道为什么必须要先wb1.Navigate(URL)一下,不然对doc.cookie 赋值会直接报错

2、用InternetGetCookie设置cookie,设置成功了但是无效,InternetSetCookie的入参我试了很多种,难道 InternetGetCookie设置成功了不能用在客户端的webbrowser?

自己从dll里面导出提取用
function GetCookie(host: string): string;
const
  INTERNET_COOKIE_HTTPONLY = 8192;
var
  hModule: THandle;
  lp: Pointer;
  InternetGetCookieEx: function(lpszUrl, lpszCookieName, lpszCookieData
    : PAnsiChar; var lpdwSize: DWORD; dwFlags: DWORD; lpReserved: pointer)
    : BOOL; stdCall;
  CookieSize: DWORD;
  CookieData: PAnsiChar;
begin
  LoadLibrary('wininet.dll');
  hModule := GetModuleHandle('wininet.dll');
  if hModule <> 0 then
  begin
    @InternetGetCookieEx := GetProcAddress(hModule, 'InternetGetCookieExA');
    if @InternetGetCookieEx <> nil then
    begin
      CookieSize := 1024;
      Cookiedata := AllocMem(CookieSize);
      if InternetGetCookieEx(PAnsiChar(AnsiString(host)), nil, Cookiedata, CookieSize, INTERNET_COOKIE_HTTPONLY, nil) then
      result:=cookiedata;
      FreeMem(Cookiedata);
    end;
  end;
end;

自己摸索实现了,给出小蜜蜂论坛顶帖机调用成功的例子


var
  cookieCount: Integer;
  I: Integer;
  hModule: THandle;
  InternetSetCookieEx: function(lpszUrl, lpszCookieName, lpszCookieData
  : PWideChar; dwFlags: DWORD; dwReserved: pointer)
  : BOOL; stdCall;
  const
  INTERNET_COOKIE_HTTPONLY = 8192;
begin
  //获取IdCookieManager1中的cookie
  cookieCount := frmMain.IdCookieManager1.CookieCollection.Count;
  if cookieCount > 0 then
  begin
    LoadLibrary('wininet.dll');
    hModule := GetModuleHandle('wininet.dll');
    if hModule <> 0 then
    begin
      @InternetSetCookieEx := GetProcAddress(hModule, 'InternetSetCookieExW');
      if @InternetSetCookieEx <> nil then
      begin
        //向IE中循环插入cookie
        for I := 0 to cookieCount - 1 do
        begin
          with frmMain.IdCookieManager1.CookieCollection.Cookies[I] do
          begin
             if not InternetSetCookieEx(PChar(URL),nil,
              PChar(CookieText), INTERNET_COOKIE_HTTPONLY, nil) then
             begin
               frmMain.ShowErrormsg('设置IE的cookie失败');
             end;
          end;
        end;
      end;
    end;
  end;
end;

发布了27 篇原创文章 · 获赞 0 · 访问量 1101

猜你喜欢

转载自blog.csdn.net/netyou/article/details/104179921