c# request interface 302 redirect cannot obtain cookie

A problem occurred: When requesting a third-party interface, I tested it with postman and could get the cookie value. In the project, the interface cannot obtain the cookie, and the return status is 302 redirect.

Solution

Set parameters: AllowAutoRedirect = false;
default value is true
true if you want the handler to automatically follow the HTTP redirect header to the new location of the resource

If AllowAutoRedirect is set to false, all HTTP responses with HTTP status codes 300 to 399 will be returned to the application

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                
                request.AllowAutoRedirect = false;
                CookieContainer cookieContainer = new CookieContainer();
                Cookie JSESSIONID = new Cookie("JSESSIONID", Global.JSESSIONID);
                JSESSIONID.Domain = "xxx.xxx.xxx.xxx";
                cookieContainer.Add(JSESSIONID);
                request.CookieContainer = cookieContainer;
                //---------------------------------------------------
                //响应
                //---------------------------------------------------
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream rspStream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(rspStream, Encoding.UTF8))
                {
                    string resRead = reader.ReadToEnd();
                    rspStream.Close();
                }

                response.Close();

Guess you like

Origin blog.csdn.net/drunk2/article/details/128316591