[英]Submit form using HttpClient in C#
我正在通過htmlagilitypack獲取網站表單,設置表單變量並嘗試提交表單。 一切看起來都很好,但表單提交的響應為空。
static void Main(string[] args)
{
string urlAddress = "mywebsite";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(urlAddress);
// Post link
var post = doc.GetElementbyId("post").GetAttributeValue("href", "");
doc = web.Load(post);
// get the form
var form = doc.DocumentNode.SelectSingleNode("//form[@class='picker']");
// get the form URI
string actionValue = form.Attributes["action"]?.Value;
System.Uri uri = new System.Uri(actionValue);
// Populate the form variable
var formVariables = new List<KeyValuePair<string, string>>();
formVariables.Add(new KeyValuePair<string, string>("id", "ho"));
var formContent = new FormUrlEncodedContent(formVariables);
// submit the form
HttpClient client = new HttpClient();
var response = client.PostAsync(uri, formContent);
}
有誰知道為什么我的變量響應為空?
謝謝
HttpClient.PostAsync
返回一個Task<HttpResponseMessage>
所以通常需要等待它。 當您在main方法中使用它時,您必須從任務中獲取結果
var response = client.PostAsync(uri, formContent).GetAwaiter().GetResult();
或者更簡單
var response = client.PostAsync(uri, formContent).Result;
在這兩種情況下,響應都是HttpResponseMessage
一個實例。 您可以檢查該實例的HTTP狀態和響應的內容。
如果使用.net核心,您甚至可以使用異步Main方法
static async Task Main(string[] args) {
//..code removed for brevity
var response = await client.PostAsync(uri, formContent);
var content = await response.Content.ReadAsStringAsync();
//...
}
你錯過了。 Result
在PostAsync
。 只需將該行更改為:
var response = client.PostAsync(uri, formContent).Result;
.Result
但是,同步運行任務。 如果存在異常使其稍微難以調試,則返回AggregateException
。
如果您使用的是Visual Studio 2017 Update 15.3或更高版本以及C#7.1,則現在支持aysnc
main
。
您可以按如下方式修改代碼:
static async Task Main()
{
string urlAddress = "mywebsite";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(urlAddress);
// Post link
var post = doc.GetElementbyId("post").GetAttributeValue("href", "");
doc = web.Load(post);
// get the form
var form = doc.DocumentNode.SelectSingleNode("//form[@class='picker']");
// get the form URI
string actionValue = form.Attributes["action"]?.Value;
System.Uri uri = new System.Uri(actionValue);
// Populate the form variable
var formVariables = new List<KeyValuePair<string, string>>();
formVariables.Add(new KeyValuePair<string, string>("id", "ho"));
var formContent = new FormUrlEncodedContent(formVariables);
// submit the form
HttpClient client = new HttpClient();
var response = await client.PostAsync(uri, formContent);
}
這將幫助您await
async
任務。 如果您收到任何異常,您將收到實際的異常而不是AggregateException
。
請務必注意,默認情況下,當前未啟用C#7.1。 要啟用7.1功能,您需要更改項目的語言版本設置。
有關詳細信息,請參閱此鏈接 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.