为特殊HTML输入创建HttpWebRequest

时间:2015-07-10 02:40:49

标签: c# httpwebrequest

我需要使用电子邮件和密码将HttpWebRequest发送到网址

<input name="Login[email]" id="Login_email" type="text" />
<input name="Login[password]" id="Login_password" type="password" />
<input type="hidden" value="f3b0997e3b6451ecee2840f353b3cf9a69805596" name="fs_csrf" />

如何使用上面的电子邮件,密码和隐藏输入字段在服务器端创建HttpWebRequest。 提前感谢你

1 个答案:

答案 0 :(得分:0)

试试这个:

//getting the hash
var req = (HttpWebRequest)WebRequest.Create("https://example.com/login");
var cookies = new CookieContainer();
req.CookieContainer = cookies;
string fs_csrf;
using (var res = req.GetResponse())
using (var resStream = res.GetResponseStream())
using (var reader = new StreamReader(resStream)) {
    fs_csrf = new Regex("input.*?hidden.*?value=\"(.*?)\"").Match(reader.ReadToEnd()).Groups[1].Value;
}
//submitting form
req = (HttpWebRequest)WebRequest.Create("https://example.com/login");
req.CookieContainer = cookies;
req.Method = "POST"; //i assume it's a post request
var buffer = Encoding.UTF8.GetBytes("Login[email]=theemail&Login[password]=thepswd&fs_csrf=" + fs_csrf);
req.ContentLength = buffer.Length;
using (var reqStream = req.GetRequestStream()) {
      reqStream.Write(buffer, 0, buffer.Length);
}
using (var res = req.GetResponse())
using (var resStream = res.GetResponseStream())
using (var reader = new StreamReader(resStream)) {
    var respStr = reader.ReadToEnd();
}