简体   繁体   中英

httpwebrequest cookies from response

How can I use the cookies from a response in a new request?

So basically I have an if statement within my getresponse stream for redirects,

Example of code -

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (Stream stream2 = response.GetResponseStream())
        {
            if ((int)response.StatusCode >= 300 && (int)response.StatusCode <= 399)
            {   
                string newurl = "https://www.example.com/page2";

                request = request = (HttpWebRequest)WebRequest.Create(newurl);

            }
            using (StreamReader reader = new StreamReader(stream2, Encoding.UTF8))
            {
                str6 = reader.ReadToEnd();
            }
        }
        return str6;
    }

How can I apply the response cookies/header data to my new request -

            request = request = (HttpWebRequest)WebRequest.Create(newurl);

I know if I do

response.Headers["Location"];

it'll give me the response location, but what about cookies? & how could i apply those cookies to the request

var myCookie = new HttpCookie("token");
myCookie.Value = Guid.NewGuid().ToString();
myCookie.Expires = DateTime.UtcNow.AddHours(10);
response.Cookies.Add(myCookie);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM