我正在尝试用c#自动填写web表单。这是我的代码,我从一个旧的堆栈溢出的帖子:
//NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formUrl = "https://url/Login/Login.aspx?ReturnUrl=/Student/Grades.aspx";
string formParams = string.Format(@"{0}={1}&{2}={3}&{4}=%D7%9B%D7%A0%D7%99%D7%A1%D7%94", usernameBoxID ,"*myusernamehere*",passwordBoxID,"*mypasswordhere*" ,buttonID);
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl); //creating the request with the form url.
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST"; // http POST mode.
byte[] bytes = Encoding.ASCII.GetBytes(formParams); // convert the data to bytes for the sending.
req.ContentLength = bytes.Length; // set the length
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string pageSource = sr.ReadToEnd();
}
用户名和密码正确。我看了看网站的来源,它有3个值输入(用户名,密码,按钮验证)。但不知何故,返回的resp
和pageSource
总是再次返回登录页面。
我不知道这是怎么回事,有什么想法吗?
你正试图以一种非常困难的方式做到这一点,尝试使用。net HttpClient:
using System;
using System.Collections.Generic;
using System.Net.Http;
class Program
{
static void Main()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:6740");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("***", "login"),
new KeyValuePair<string, string>("param1", "some value"),
new KeyValuePair<string, string>("param2", "some other value")
});
var result = client.PostAsync("/api/Membership/exists", content).Result;
if (result.IsSuccessStatusCode)
{
Console.WriteLine(result.StatusCode.ToString());
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
}
else
{
// problems handling here
Console.WriteLine( "Error occurred, the status code is: {0}", result.StatusCode);
}
}
}
}
检查这个答案,可能有帮助:. net HttpClient。如何POST字符串值?