Transfer Authentication from Webbrowser to Indy CookieManager

前端 未结 1 1003
北恋
北恋 2020-12-20 06:04

How do you put the cookie from the Webbrowser to an Indy CookieManager for Http Request.

I get the cookies after i login in to a website like this..

Test Pro

相关标签:
1条回答
  • 2020-12-20 06:39

    Since you tagged your question with multiple Delphi version tags, I assume you are using different releases of Indy with each Delphi version, is that right? Indy's cookie handling logic has changed a bit over the years, and underwent a major re-wrote in early 2011 to account for RFC 6265 (which obsoleted all previous cookie RFCs).

    Under the current Indy 10 release, adding cookies manually is done using the TIdCookieManager.AddServerCookie() or TIdCookieManager.AddServerCookies() method:

    procedure AddServerCookie(const ACookie: String; AURL: TIdURI);
    procedure AddServerCookies(const ACookies: TStrings; AURL: TIdURI);
    

    Both parameters are required, where ACookie is a name=value; parameters string for a single cookie, and AURL is the URL where the cookie came from (used for validating the cookie data and initializing any default values where needed), for example:

    procedure TForm1.WebBrowser1DownloadComplete(Sender: TObject);
    var
      document: IHTMLDocument2;
      cookies: TStringList;
      uri: TIdURI;
    begin
      document := WebBrowser1.Document as IHTMLDocument2;
      cookies := TStringList.Create;
      try
        // fill cookies as needed, one cookie per line
        uri := TIdURI.Create(document.URL);
        try
          IdCookieManager1.AddServerCookies(cookies, uri);
        finally
          uri.Free;
        end;
      finally
        cookies.Free;
      end;
    end;
    

    Keep in mind that the document.cookie property can contain multiple cookies in it, so you will have to split the cookies up manually before you can then pass them to TIdCookieManager. Also, the document.cookie property uses the ; character to separate cookies, but it also uses ';' for separating the name=value and parameters values for a single cookie, so you are going to have to do a little bit of parsing when splitting up the document.cookie data.

    0 讨论(0)
提交回复
热议问题