use*_*563 4 c# httpresponse httpclient html-agility-pack
我正在通过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);
}
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么我的变量响应为空?
谢谢
HttpClient.PostAsync返回一个Task<HttpResponseMessage>通常需要等待的结果。在主要方法中使用它时,您必须从任务中获取结果
var response = client.PostAsync(uri, formContent).GetAwaiter().GetResult();
Run Code Online (Sandbox Code Playgroud)
或更简单
var response = client.PostAsync(uri, formContent).Result;
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,response都是的一个实例HttpResponseMessage。您可以检查该实例的HTTP状态和响应的内容。
如果使用.net core,甚至可以使用异步Main方法,例如
static async Task Main(string[] args) {
//..code removed for brevity
var response = await client.PostAsync(uri, formContent);
var content = await response.Content.ReadAsStringAsync();
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5130 次 |
| 最近记录: |