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).
HttpWebRequest does not implement IDisposable so it does not require disposing. just set the httprequest object to null once your done with it.
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.
WebRequest is an abstract class. The HttpWebRequest class allows you to programmatically make web requests to the HTTP server.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With