编程语言
首页 > 编程语言> > 在C#中使用HttpClient提交表单

在C#中使用HttpClient提交表单

作者:互联网

我正在通过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>因此通常需要等待.在主要方法中使用它时,您必须从任务中获取结果

var response = client.PostAsync(uri, formContent).GetAwaiter().GetResult();

或更简单

var response = client.PostAsync(uri, formContent).Result;

在这两种情况下,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();
    //...
}

标签:httpclient,httpresponse,html-agility-pack,c
来源: https://codeday.me/bug/20191025/1930336.html