1
我想使用WebRequest
登錄網站,稍後在WebBrowser
中顯示網站(記錄)。在WebBrowser中使用WebRequest cookie
但如何「複製」WebRequest
cookie到WebBrowser
?
由於提前,
卡茨珀
我想使用WebRequest
登錄網站,稍後在WebBrowser
中顯示網站(記錄)。在WebBrowser中使用WebRequest cookie
但如何「複製」WebRequest
cookie到WebBrowser
?
由於提前,
卡茨珀
使用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;
}
現在你得到餅乾,你只需要將其設置爲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?它適用於各種系統和東西? – Kacper 2012-02-25 11:42:49
嗯,這是一個很好的問題,但對不起,我還不確定,但這就是我發現我怎麼才能真正做到這一點,Webrowser控件似乎只是使用IE瀏覽器,所以cookie應該與IE共享,如果你知道一些更好的請讓我知道,謝謝 – 2012-02-25 11:57:07