如何在HttpWebRequest中使用cookies

时间:2010-06-04 08:48:07

标签: .net httpwebrequest cookies

我正在从网页创建一个数据检索应用程序。该页面受密码保护,当用户登录时,会创建cookie。

为了检索应用程序首先必须登录的数据:使用用户名和密码发出Web请求并存储cookie。然后,当存储cookie时,必须将其添加到所有请求的标题中。

以下是发出请求和检索内容的方法:

public void getAsyncDailyPDPContextActivationDeactivation()
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(dailyPDPContextActivationDeactivation);

    IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);

    asyncResult.AsyncWaitHandle.WaitOne();

    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
    using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        string responseText = responseStreamReader.ReadToEnd();
    }
}

有人知道如何修改此方法以便在标题中添加Cookie吗?

如果有人建议从响应中存储cookie的方式(当应用程序发出请求http:xxx.xxx.xxx/login?username = xxx& password = xxx时,cookie已创建并且必须存储以备将来使用)。

2 个答案:

答案 0 :(得分:36)

CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest.CookieContainer = cookieContainer;

然后在后续请求中重用此CookieContainer:

HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest2.CookieContainer = cookieContainer;

答案 1 :(得分:0)

使用CookieContainer或您可以使用CookieAwareWebClient