C # Sending a cookie in an HttpWebRequest which is being redirected

I am looking for a way to work with an API that requires a login and then redirects to a different URL.
The thing is, so far I have only come up with a way to make 2 Http requests for every action I want to do: first, get a cookie with AllowRedirect = false, and then get the actual URI and make a second request with a cookie

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sUrl); request.AllowAutoRedirect = false; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string redirectedUrl = response.Headers["Location"]; if (!String.IsNullOrEmpty(redirectedUrl)) { redirectedUrl = "http://www.ApiUrlComesHere.com/" + redirectedUrl; HttpWebRequest authenticatedRequest = (HttpWebRequest)WebRequest.Create(redirectedUrl); authenticatedRequest.Headers["Cookie"] = response.Headers["Set-Cookie"]; response = (HttpWebResponse)request.GetResponse(); } 

Seems terribly ineffective. Is there another way?
Thanks!

+4
source share
2 answers

Seems terribly ineffective.

Why?

In the end, this is all HttpWebRequest , with AllowAutoRedirect true will do.

0
source
 public String Post(String url, IDictionary<String, String> data) { String requestData = String.Join("&", data.Select(x => String.Format("{0}={1}", HttpUtility.UrlEncode(x.Key), HttpUtility.UrlEncode(x.Value)))); Byte[] requestBytes = Encoding.UTF8.GetBytes(requestData); CookieContainer cookies = new CookieContainer(); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.CookieContainer = cookies; request.Method = WebRequestMethods.Http.Post; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = requestBytes.Length; request.AllowAutoRedirect = false; Stream requestStream = request.GetRequestStream(); requestStream.Write(requestBytes, 0, requestBytes.Length); requestStream.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; while (response.StatusCode == HttpStatusCode.Found) { response.Close(); String location = response.Headers[HttpResponseHeader.Location]; request = WebRequest.Create(location) as HttpWebRequest; request.CookieContainer = cookies; request.Method = WebRequestMethods.Http.Get; response = request.GetResponse() as HttpWebResponse; } String responseData = this.Read(response.GetResponseStream()); response.Close(); return (responseData); } 
+1
source

Source: https://habr.com/ru/post/1307931/


All Articles