Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get cookies from httpwebrequest

Tags:

c#

cookies

I'm trying to get all cookies from a website using this code

        CookieContainer cookieJar = new CookieContainer();

        var request = (HttpWebRequest)HttpWebRequest.Create("http://www.foetex.dk/ugenstilbud/Pages/Zmags.aspx");
        request.CookieContainer = cookieJar;

        var response = request.GetResponse();

        foreach (Cookie c in cookieJar.GetCookies(request.RequestUri))
        {
            Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value);
        }

        Console.ReadLine();

The only thing i want is to display with console.writeline, but im not getting a single of them.

like image 448
Peter Avatar asked May 05 '13 00:05

Peter


2 Answers

//Please use this,
HttpWebRequest request = null;
request = HttpWebRequest.Create(StringURL) as HttpWebRequest;                
HttpWebResponse TheRespone = (HttpWebResponse)request.GetResponse();
String setCookieHeader = TheRespone.Headers[HttpResponseHeader.SetCookie];
like image 72
Mnyikka Avatar answered Sep 28 '22 10:09

Mnyikka


The following example uses the HttpCookie class and its properties to read a cookie with a specific name.

HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");

Retrieve the values in the HttpWebResponse.Cookies property of HttpWebResponse. In this example, the cookies are retrieved and saved to isolated storage:

private void ReadCallback(IAsyncResult asynchronousResult)
{
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse)
        request.EndGetResponse(asynchronousResult);
    using (IsolatedStorageFile isf =
        IsolatedStorageFile.GetUserStoreForSite())
    {
        using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies",
            FileMode.OpenOrCreate, FileAccess.Write))
        {
            using (StreamWriter sw = new StreamWriter(isfs))
            {
                foreach (Cookie cookieValue in response.Cookies)
                {
                    sw.WriteLine("Cookie: " + cookieValue.ToString());
                }
                sw.Close();
            }
        }

    }
}
like image 32
Obama Avatar answered Sep 28 '22 10:09

Obama