C#WebBrowser怎么获取和设置Cookie的方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#WebBrowser怎么获取和设置Cookie的方法相关的知识,希望对你有一定的参考价值。

参考技术A 1.在WebBrowser中获取Cookie

CookieContainer myCookieContainer = new CookieContainer();

string cookieStr = webBrowser1.Document.Cookie;
string[] cookstr = cookieStr.Split(';');
foreach (string str in cookstr)

string[] cookieNameValue = str.Split('=');
Cookie ck = new Cookie(cookieNameValue[0].Trim ().ToString(), cookieNameValue[1].Trim ().ToString());
ck.Domain = "www.google.com";
myCookieContainer.Add(ck);


WebClient设置cookie!
WebClient wc = new WebClient();
wc.Headers.Add("Cookie", "phpSESSID=" + cookie + ";");
// 注意,这里是Cookie,不是Set-Cookie
byte[] re = wc.UploadData(Global.RootPath + "test.php", new byte[0]);
System.Text.UTF8Encoding converter = new System.Text.UTF8Encoding();
string str = converter.GetString(re);

2. 在WebBrowser中设置Cookie
public partial class WebBrowserControl : Form

private String url;

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

public WebBrowserControl(String path)

this.url = path;
InitializeComponent();

// set cookie
InternetSetCookie(url, "JSESSIONID", Globals.ThisDocument.sessionID);

// navigate
webBrowser.Navigate(url);



3.将WebBrowser的cookie信息传给HttpWebRequest

先建一个"CookieContainer" 把WebBrowser中的Cookie保存在里面

//在WebBrowser中登录cookie保存在WebBrowser.Document.Cookie中
CookieContainer myCookieContainer = new CookieContainer();

//String 的Cookie 要转成 Cookie型的 并放入CookieContainer中
string cookieStr = webBrowser1.Document.Cookie;
string[] cookstr = cookieStr.Split(';');

foreach (string str in cookstr)

string[] cookieNameValue = str.Split('=');
Cookie ck = new Cookie(cookieNameValue[0].Trim().ToString(), cookieNameValue[1].Trim().ToString());
ck.Domain = "www.abc.com";//必须写对
myCookieContainer.Add(ck);


HttpWebRequest hreq = (HttpWebRequest)HttpWebRequest.Create("http://www.abc.com/search.asp");
hreq.Method = "POST";
hreq.ContentType = "application/x-www-form-urlencoded";

//自己创建的CookieContainer
hreq.CookieContainer = myCookieContainer;

string postdata = "id=2005&action=search&name=";
byte[] byte1 = Encoding.ASCII.GetBytes(postdata);
hreq.ContentLength = byte1.Length;

Stream poststream = hreq.GetRequestStream();
poststream.Write(byte1, 0, byte1.Length);
poststream.Close();

HttpWebResponse hres = (HttpWebResponse)hreq.GetResponse();本回答被提问者和网友采纳

WinForm WebBrowser 设置cookie

[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
private void test(){

    string cookie = "name=小明; age=19;phone=13013139876"//需要设置到Webbrowser的Cookie信息
    string url = "http://192.168.1.12/data/2016/student.htm";//访问地址
    string domain = "/data/2016";//目标主机域名
    foreach (string c in cookie.Split(;))
    {
      string[] item = c.Split(=);
       if (item.Length == 2)
          {
           InternetSetCookie(url, null, new Cookie(HttpUtility.UrlEncode(item[0]).Replace("+", ""), HttpUtility.UrlEncode(item[1]), "; expires = Session GMT", "/").ToString());
                }
            }
            webBrowser1.Navigate(url);
} 


要注意上面的代码.Replace(“+”, “”),我被这个困惑了半天,导致Cookie只有第一个字段name设置成功,后面的age,phone字段都没设置成功,通过抓包分析,发现设置后的Cookie字段前面多了个”+”号,都说细节决定成败,确实如此。这个”+”号应该是HttpUtility.UrlEncode()编码后导致的,但是如果你不进行HttpUtility.UrlEncode()编码是绝对不行的,所以我们只好通过.Replace(“+”, “”)过滤掉”+”号,至此Cookie已经完美设置成功。

还有就是可能你手动设置Cookie的过程中由于传参错误或其他原因导致webbrowser打开url提示错误500之类的,这时候需要手动打开电脑的IE浏览器,然后清除缓存记录Cookie等。就可以正常打开url了。




原文链接:https://blog.csdn.net/hangom/article/details/52619394

以上是关于C#WebBrowser怎么获取和设置Cookie的方法的主要内容,如果未能解决你的问题,请参考以下文章

C#WebBrowser怎么获取和设置Cookie的方法

C#WebBrowser怎么获取和设置Cookie的方法

如何设置WebBrowser 的Cookie?

C#下利用WebBrowser完整获取COOKIE

webbrowser如何获取cookie中的sessionid

webbrowser怎么清空cookies