C# 在WebBrowser中使用WebRequestCookie
我想使用C# 在WebBrowser中使用WebRequestCookie,c#,httpwebrequest,webbrowser-control,C#,Httpwebrequest,Webbrowser Control,我想使用WebRequest登录站点,然后在WebBrowser中显示站点(已登录) 但是如何将WebRequestcookie“复制”到WebBrowser 提前感谢, Kacper使用cookie collection获取cookie,本月我编写了类似的内容,我可以与您分享一些示例代码: static string GetFromServer(string URL, ref CookieCollection oCookie) { //first rquest
WebRequest
登录站点,然后在WebBrowser
中显示站点(已登录)
但是如何将WebRequest
cookie“复制”到WebBrowser
提前感谢,
Kacper使用cookie collection获取cookie,本月我编写了类似的内容,我可以与您分享一些示例代码:
static string GetFromServer(string URL, ref CookieCollection oCookie)
{
//first rquest
// Create a request for the URL.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
request.AllowAutoRedirect = false;
// If required by the server, set the credentials.
//request.Credentials = CredentialCache.DefaultCredentials;
request.CookieContainer = new CookieContainer();
if (oCookie != null)
{
foreach (Cookie cook in oCookie)
{
request.CookieContainer.Add(cook);
}
}
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cook in response.Cookies)
{
oCookie.Add(cook);
}
// Display the status.
while (response.StatusCode == HttpStatusCode.Found)
{
response.Close();
request = (HttpWebRequest)HttpWebRequest.Create(response.Headers["Location"]);
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
if (oCookie != null)
{
foreach (Cookie cook in oCookie)
{
request.CookieContainer.Add(cook);
}
}
response = (HttpWebResponse)request.GetResponse();
foreach (Cookie cook in response.Cookies)
{
oCookie.Add(cook);
}
}
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams and the response.
reader.Close();
response.Close();
return responseFromServer;
}
现在您得到了cookies,只需将其设置为webBrowser控件,即可导入此方法:
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
当你得到饼干后,就叫这个:
string cookie_string = string.Empty;
foreach (Cookie cook in cookieCon)
{
cookie_string += cook.ToString() + ";";
InternetSetCookie(url, cook.Name, cook.Value);
}
webBrowser1.Navigate(url, "", null, "Cookie: " + cookie_string + Environment.NewLine);
请注意,这只是我的测试代码,主要是从msdn复制的,因此它可能有缺陷,您可能需要更多的异常处理我应该依赖wininet.dll吗?它适用于各种系统和东西?嗯,这是一个很好的问题,但很抱歉,我还不太确定,但这就是我发现如何才能真正做到的,WebBrowser控件似乎只是在使用IE,所以cookie应该与IE共享,如果你知道一些更好的方法,请务必让我知道,谢谢