在 C# 中使用 HttpClient 提交表单

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 return a 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();
    //...
}

您的 PostAsync 中缺少 .Result。只需将行更改为:

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

.Result 但是,同步运行任务。它 returns 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 功能,您需要更改项目的语言版本设置。

有关详细信息,请参阅此 link