2

So I am experimenting a little bit with HttpWebRequests and the System.Net; namespace in general and I did a GET request using POSTMAN and I got 3 cookies, now I tried doing the same request with C# but it doesnt seem to return any cookies at all. Or it might but it's probably me who's doing this in a bad manner. What is the propper way of doing a GET request and capturing the cookies so that I can later use them for a POST.

This is what I've got. And it seems as if cookieContainer is empty once it finishes running, I tried debugging aswell.

public static void TestGET()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://www.instagram.com/accounts/emailsignup/");
            var cookieContainer = new CookieContainer();

            using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
            {
                using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    foreach (Cookie cookie in httpWebResponse.Cookies)
                    {
                        cookieContainer.Add(cookie);
                    }
                }
            }
        }
Aleks Goob
  • 21
  • 1

1 Answers1

0

Are you talking about the 3 Set-Cookies values in the response header. If so the code below will get those.

If you're using HttpWebResponse (this is what you're using)

using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
     var result = httpWebResponse.Headers["Set-Cookie"];
}

If you're using HttpResponseMessage:

if (httpResponse.Headers.TryGetValues("Set-Cookie", out values))
{
    var session = values;
}

The cookie container is empty because httpWebResponse.Cookies is empty as well.

References:

How to read HTTP header from response using .NET HttpWebRequest API?

How to get an specific header value from the HttpResponseMessage

ismael.
  • 418
  • 2
  • 7