我需要使用POST方法将HTTP请求发送到Asp.Net表单,此表单是一个包含3个控件的登录表单:
我尝试了以下代码:
string getUrl = "http://url/login.aspx";
string postData = String.Format("x={0}&P={1}", "usernamevalue", "passwordvalue");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
string sourceCode = sr.ReadToEnd();
}
当检索字符串SourceCode时,它返回登录页面的HTML,尽管它应该返回主页,该主页在成功提交登录后重定向到它。
我认为代码不使用提交按钮,我需要通过将数据传递给控件并单击按钮提交来解决此问题,然后获取主页的响应(成功登录后)而不是登录页面响应。
提前致谢。
答案 0 :(得分:0)
使用cookiecontainer获取响应cookie。然后使用相同的cookie容器向主页发送请求。
如果您的登录请求成功,则Response可能会将cookie添加到响应中。 所以你可以在每个页面上使用相同的cookie
var cookieContainer = new CookieContainer();
getRequest.CookieContainer = cookieContainer;
...
//send request to login.aspx page.
HttpWebRequest homeRequest = (HttpWebRequest)WebRequest.Create(homeUrl);
homeRequest.CookieContainer = cookieContainer;
//send request to homepage