How to Add Cookies to Webrequest

How to add cookies to WebRequest?

Based on your comments, you might consider writing an extension method:

public static bool TryAddCookie(this WebRequest webRequest, Cookie cookie)
{
HttpWebRequest httpRequest = webRequest as HttpWebRequest;
if (httpRequest == null)
{
return false;
}

if (httpRequest.CookieContainer == null)
{
httpRequest.CookieContainer = new CookieContainer();
}

httpRequest.CookieContainer.Add(cookie);
return true;
}

Then you can have code like:

WebRequest webRequest = WebRequest.Create( uri );
webRequest.TryAddCookie(new Cookie("someName","someValue"));

how to use cookies with HttpWebRequest

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;

Passing cookies to httpwebrequest

I'm not sure why you would want to ignore the existence of an existing mechanism and reinvent the wheel, possibly including bugs solved by the existing implementation.

Setting cookies is trivial though:

request.Headers["Cookie"] = "foo=bar";

Just as reading them from the response:

string cookieHeader = response.Headers["Set-Cookie"];

Send Cookies With HttpWebRequest

Using Justin and Rajeesh's answer here: Using CookieContainer with WebClient class I sent the cookies manually like this:

        string login_info = "login=login&redirect=http%3A%2F%2F"+WebUtility.UrlEncode(populated_config.domain)+"%2Fchat%2F%3FchannelName%3DPublic&username=" + WebUtility.UrlEncode(populated_config.username) + "&password=" + WebUtility.UrlEncode(populated_config.password) + "&channelName=Public&lang=en&submit=Login";
request = (HttpWebRequest)WebRequest.Create(populated_config.domain + "ucp.php?mode=login");
request.Method = "POST";
//manually populate cookies
Console.WriteLine(cc.GetCookieHeader(new Uri(populated_config.domain)));
request.Headers.Add(HttpRequestHeader.Cookie,cc.GetCookieHeader(new Uri(populated_config.domain)));
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write(login_info);
response = (HttpWebResponse)request.GetResponse();

How to send cookie with HttpWebRequest in c#

You need to set the cookie container of the HTTP request. Add the following line after you create the HtppWebRequest.

myReq.CookieContainer = gaCookies

How do I know which cookie(s) are must to make a correct HttpWebRequest?

The cookies required to get content from a server are specified by that server in the HTTP response's "Set-Cookie" header. The generic scenario is:

  1. Client makes an HTTP request to the server (this could be a login page, or a download page)
  2. Server responds with HTTP response that contains "Set-Cookie" header(s)
  3. Client remembers all those cookies
  4. Client uses the cookies stored in step 3 for all subsequent requests to the same server

Now, considering your scenario of integrating into Chrome, I imagine that the initial requests (steps 1 to 3) will not be done by your application, but by the Chrome itself. The cookies will be stored in the Chrome's cookie store. So what your application will need to do is to get from Chrome all cookies for the domain where you want to download from, and include those cookies in your request (step 4).

See chrome.cookies document on how to use Chrome API to interact with its cookie store, and Set-Cookie docs from Mozilla for the in-depth description of how cookies are specified in the HTTP response.

Cookies and C# HttpWebRequest

The CookieContainer should be considered similar to a browser's cookie cache for a particular site. The idea is that you supply the container as part of the request, and then it's populated by the cookies you receive and you can reuse that container for subsequent requests. When you make a request, the cookies in the container are sent with the request (just like the browser would with stored cookies).

So, for example, if you have a page that uses cookies to store an authentication token, you can pass the cookie container with the login request, and then pass it with subsequent requests which require an authenticated cookie.

As to why you can't simply extract it from the request, I guess Microsoft just didn't want to duplicate things when you can pass in a reference to a mutable cookie container in the request.

HttpWebRequest: Add Cookie to CookieContainer - ArgumentException (Parametername: cookie.Domain)

CookieContainers can hold multiple cookies for different websites, therefor a label (the Domain) has to be provided to bind each cookie to each website. The Domain can be set when instantiating the individual cookies like so:

Cookie chocolateChip = new Cookie("CookieName", "CookieValue") { Domain = "DomainName" };

An easy way to grab the domain to is to make a Uri (if you aren't using one already) that contains your target url and set the cookie's domain using the Uri.Host property.

CookieContainer gaCookies = new CookieContainer();
Uri target = new Uri("http://www.google.com/");

gaCookies.Add(new Cookie("__utmc", "#########") { Domain = target.Host });


Related Topics



Leave a reply



Submit