【问题标题】:Submit form using HttpClient in C#在 C# 中使用 HttpClient 提交表单
【发布时间】:2017-09-29 11:19:51
【问题描述】:

我通过 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);

    }

有人知道为什么我的变量响应为空吗?

谢谢

【问题讨论】:

  • 您是否收到回复,如果收到,开发者控制台中会显示什么内容?
  • 它说:Id = 3,Status = WaitingForActivation,Method = "{null}",Result = "{Not yet computed}"
  • @user6824563,你必须awaitTaskPostAsync返回
  • 我该怎么做?我正在我的主要功能中运行所有内容
  • @user6824563 显示主要功能。这样可以提供建议。

标签: c# httpclient html-agility-pack httpresponse


【解决方案1】:

HttpClient.PostAsync 返回一个Task&lt;HttpResponseMessage&gt;,所以通常需要等待它。当您在 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();
    //...
}

【讨论】:

  • 我改成 client.PostAsync(uri, formContent).Result 但它被捕获在 Exception: InnerException {"The server commit a protocol violation. Section=ResponseStatusLine"} System.Exception {System.Net .WebException}
  • @user6824563 你将不得不检查导致该错误的原因stackoverflow.com/questions/18496451/…
  • 会不会和我做的网站有关?
  • 看起来那样。该错误通常与服务器端错误有关
  • 那么你的问题基本上是如何使用 htmlagilitypack 搜索/抓取 craigslist。
【解决方案2】:

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

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 功能,您需要更改项目的语言版本设置。

更多详情请参考link

【讨论】:

    猜你喜欢
    • 2016-03-01
    • 2016-01-09
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多