在C#中重用与HttpWebRequest的连接 [英] Reuse Connection with HttpWebRequest in C#
问题描述
我需要使用.Net发出POST请求。
I need to make a POST request using .Net.
我可以通过GET进行身份验证,因此我尝试在同一个连接上发出POST请求以保证我的身份验证。
I can authenticate by GET, and so I’m trying to make a POST request on the same connection to keep my authentication.
问题是我得到401 Not Authenticated异常,这意味着连接没有被重用。
The problem is I get a 401 Not Authenticated exception, which implies the connection hasn’t been reused.
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¶m2=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.
}
编辑:有一些建议我需要传输cookie。以下内容也不起作用:
There has been some suggestions that I need to transfer cookies. The following doesn’t work either:
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¶m2=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.
}
推荐答案
你不这样做的原因保持登录是因为你没有给HttpWebRequest一个CookieContainer来保持会话ID。
The reason you don't stay logged in is because you don't give the HttpWebRequest a CookieContainer to keep the session id in.
请参阅下面的StackOverflow Q& A的可能解决方案:
See the following to StackOverflow Q&A's for your possible solution:
C#keep session id通过httpwebrequest
我希望这会有所帮助。
这篇关于在C#中重用与HttpWebRequest的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!