在C#中重用与HttpWebRequest的连接

时间:2012-01-26 20:46:39

标签: c# http httpwebrequest httprequest

我需要使用.Net发出POST请求。

我可以通过GET进行身份验证,因此我尝试在同一连接上发出POST请求以保持身份验证。

问题是我得到401 Not Authenticated异常,这意味着连接没有被重用。

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&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.
}
编辑:有一些建议我需要传输cookie。以下内容也不起作用:

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&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.
}

2 个答案:

答案 0 :(得分:5)

你没有保持登录的原因是因为你没有给HttpWebRequest一个CookieContainer来保持会话ID。

请参阅以下内容,了解StackOverflow Q& A的可能解决方案:

C# keep session id over httpwebrequest

Multiple WebRequest in same session

我希望这会有所帮助。

答案 1 :(得分:2)

知道如何在另一端管理身份验证吗? IE浏览器。如果它设置了Cookie,那么您需要确保对此进行说明,请参阅此page,特别是此说明:

  

请注意

     

出于安全原因,默认情况下会禁用Cookie。如果您想使用cookie,请使用CookieContainer属性启用cookie。