Note that there are some explanatory texts on larger screens.

plurals
  1. POReuse Connection with HttpWebRequest in C#
    text
    copied!<p>I need to make a POST request using .Net. </p> <p>I can authenticate by GET, and so I’m trying to make a POST request on the same connection to keep my authentication.</p> <p>The problem is I get a 401 Not Authenticated exception, which implies the connection hasn’t been reused. </p> <pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("my-server"); request.Credentials = new NetworkCredential("user", "password"); request.GetResponse().Close(); // Works fine // Now the request I want to make... request = (HttpWebRequest)WebRequest.Create("my-server"); request.Credentials = new NetworkCredential("user", "password"); request.Method = "post"; string postData = "param1=1&amp;param2=2"; byte[] data = new ASCIIEncoding().GetBytes(postData); request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); stream.Close(); request.GetResponse().Close(); // This line gets a 401 Not Authorized error. } </code></pre> <p>EDIT: There has been some suggestions that I need to transfer cookies. The following doesn’t work either:</p> <pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("my-server"); request.Credentials = new NetworkCredential("user", "password"); var response = (HttpWebResponse)request.GetResponse(); var cookieContainer = new CookieContainer(); foreach (Cookie cookie in response.Cookies) { cookieContainer.Add(cookie); } response.Close(); // Now the request I want to make... request = (HttpWebRequest)WebRequest.Create("my-server"); request.Credentials = new NetworkCredential("user", "password"); request.CookieContainer = cookieContainer; request.Method = "post"; string postData = "param1=1&amp;param2=2"; byte[] data = new ASCIIEncoding().GetBytes(postData); request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); request.GetResponse().Close(); // This line gets a 401 Not Authorized error. } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload