Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 httpWebResponse = (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).

like image 730
Niko Gamulin Avatar asked Jun 04 '10 08:06

Niko Gamulin


People also ask

Should I dispose HttpWebRequest?

HttpWebRequest does not implement IDisposable so it does not require disposing. just set the httprequest object to null once your done with it.

What is cookie container?

A CookieContainer is a data structure that provides storage for instances of the Cookie class, and which is accessed in a database-like manner. The CookieContainer has a capacity limit that is set when the container is created or changed by a property.

What is the difference between HttpWebRequest and WebRequest?

WebRequest is an abstract class. The HttpWebRequest class allows you to programmatically make web requests to the HTTP server.

What is HttpWebRequest C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP. Do not use the HttpWebRequest constructor.


1 Answers

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; 
like image 53
k_b Avatar answered Sep 28 '22 07:09

k_b