[英]Filling a Web Form in C#
I'm trying to fill a web form automatically with C#. 我正在尝试使用C#自动填充Web表单。 Here is my code i took from an old stack overflow post:
这是我从旧堆栈溢出帖子中获取的代码:
//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();
}
The username and password are correct. 用户名和密码正确。 I looked at the source of the website and it has 3 values to enter(username , password , button validation).
我查看了网站的来源,并输入了3个值(用户名,密码,按钮验证)。 But somehow the
resp
and the pageSource
that return are always the login page again. 但是以某种方式返回的
resp
和pageSource
始终都是登录页面。
i have no idea what is that keep happening ,any ideas? 我不知道那是怎么回事,有什么想法吗?
You are trying to do it in a very hard way, try using .Net HttpClient: 您正在尝试以非常困难的方式进行操作,请尝试使用.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);
}
}
}
}
Check this answer, might help: .NET HttpClient. 检查此答案,可能会有所帮助: .NET HttpClient。 How to POST string value?
如何发布字符串值?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.