获取登录cookieColletion在cef里面打开网页
public static BaseResult getHTML(string url, Encoding encoding, string cookieString) { CookieContainer loginCookies = new CookieContainer(); BaseResult result = new BaseResult(); HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url); //建立HttpWebRequest對象 hwr.Method = "GET"; hwr.Timeout = 60000; //定義服務器超時時間 //hwr.AllowAutoRedirect = false; hwr.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.65 Safari/537.36"; hwr.Headers.Add("content", "text/html; charset=GBK"); if (cookieString != null) { hwr.Headers.Add("Cookie", cookieString); } else { hwr.CookieContainer = loginCookies; } HttpWebResponse hwResponse = null; try { lock (obj) { hwResponse = (HttpWebResponse)hwr.GetResponse(); //取得回應 //判断HTTP响应状态 if (hwResponse.StatusCode != HttpStatusCode.OK) { result.Code = 0; result.Message = "访问失败!状态码:" + hwResponse.StatusCode; } else { result.Code = 1; result.Message = "成功"; Stream s = hwResponse.GetResponseStream(); //得到回應的流對象 StreamReader sr = new StreamReader(s, encoding); //以UTF-8編碼讀取流 StringBuilder content = new StringBuilder(); // while (sr.Peek() != -1) //每次讀取一行,直到 { //下一個字節沒有內容 content.Append(sr.ReadLine()); //返回為止 } result.Content = content.ToString(); result.Cookie = hwResponse.Headers.Get("Set-Cookie"); result.cookieColletion = hwResponse.Cookies; } } } catch (Exception ex) { result.Code = -1; result.Message = "请求失败,请检查地址"; result.Content = ex.ToString(); } finally { if (hwResponse != null) { hwResponse.Close(); } hwr = null; } return result; }
设置
private void SetCefCookies(string url, CookieCollection cookies) { CefSharp.Cef.GetGlobalCookieManager().SetStoragePath(Environment.CurrentDirectory, true); foreach (System.Net.Cookie c in cookies) { var cookie = new CefSharp.Cookie { Creation = DateTime.Now, Domain = c.Domain, Name = c.Name, Value = c.Value, Expires = c.Expires }; CefSharp.Cef.GetGlobalCookieManager().SetCookie(url, cookie); } }