Reputation: 268
I want to login to a site using WebRequest
and later show site (logged) in WebBrowser
.
But how to "copy" WebRequest
cookie into WebBrowser
?
Thanks in advance,
Kacper
Upvotes: 1
Views: 5685
Reputation: 2963
use cookie collection to grab cookies, I've write something similar this month and I can share you some sample code:
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;
}
Now you got cookies, and you just need to set it to the webBrowser control, import this method:
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
and call this after you got cookies:
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);
Please be aware of that this is just my test code and mainly was copied from msdn so it may buggy and you may need more exception handling
Upvotes: 3