我想添加Cookie并获取http网站来源 如何将Cookie添加到我的代码中,当getresponse()网站读取我的Cookies?
enter code here
WebRequest scienceRequest = WebRequest.Create("http://www.google.com");
WebResponse scienceResponse = scienceRequest.GetResponse();
Stream ReceiveStream = scienceResponse.GetResponseStream();
scienceResponse = scienceRequest.GetResponse();
ReceiveStream = scienceResponse.GetResponseStream();
StreamReader readStream = new StreamReader(ReceiveStream, encode);
string strResponse = readStream.ReadToEnd();
readStream.Close();
scienceResponse.Close();
答案 0 :(得分:0)
我找到this:
private void ReadCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)
request.EndGetResponse(asynchronousResult);
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForSite())
{
using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(isfs))
{
foreach (Cookie cookieValue in response.Cookies)
{
sw.WriteLine("Cookie: " + cookieValue.ToString());
}
sw.Close();
}
}
}
}
答案 1 :(得分:0)
您可以使用CookieContainer
。您可以使用
CookieContainer cookieJar = new CookieContainer();
// Optionally add some values to the container
cookieJar.Add(new Uri("http://www.domain.com"), new Cookie("name", "Raeled"));
然后,您可以将容器附加到您的请求中(您可以反复执行此操作以继续使用相同的Cookie):
(scienceRequest as HttpWebRequest).CookieContainer = cookieJar;
然后,网页将使用容器中的cookie,并在需要时更改它们。 如果网页更改了它们,您可以使用以下内容阅读它们:
CookieCollection collection = cookieJar.GetCookies(new Uri("http://www.domain.com"));
string myValue = collection["name"].Value;
获取或设置您需要提供URI,因为CookieContainer可以在单个CookieContainer
中跟踪差异域的Cookie。