开发者

how to use cookies with HttpWebRequest

I am creating an application for data retrieval from the web page. The page is password protected and when the user logs in the cookie is created.

In order to retrieve the data the application first has to log in: make web request with username and password and store the cookie. Then when the cookie is stored it has to be added into the headers of all requests.

Here is the method which makes requests and retrieves the content:

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

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

    asyncResult.AsyncWaitHandle.WaitOne();

    using (HttpWebResponse httpWebRe开发者_开发百科sponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
    using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        string responseText = responseStreamReader.ReadToEnd();
    }
}

Does anyone know how to modify this method in order to add a cookie into the header?

I would be also thankful if anyone suggested a way to store cookie from the response (when the application makes a request http:xxx.xxx.xxx/login?username=xxx&password=xxx the cookie is created and has to be stored for future requests).


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

Then you reuse this CookieContainer in subsequent requests:

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


Use the CookieContainer or you could use a CookieAwareWebClient

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜