0

我想添加 Cookie 并获取 http 网站源如何将 Cookie 添加到我的代码中,以及当 getresponse() 网站读取我的 Cookie 时?

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();
4

2 回答 2

0

您可以CookieContainer为此使用 a 。您可以使用

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.

于 2012-10-26T19:17:21.927 回答
0

我发现了这个

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();
            }
        }

    }
}
于 2012-10-26T19:16:32.183 回答