[英]Filling a Web Form in C#
我正在嘗試使用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。 如何發布字符串值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.