c# - 如何在 C# 中发送带有表单数据的 POST

标签 c#

我正在尝试制作一个程序,该程序使用用户名、密码、硬件 ID 和 POST 中的 key 请求我的网站。
我这里有这段代码,它应该使用该表单数据向我的网站发送 POST 请求,但是当它发送时,我的网络服务器报告说它没有收到 POST 数据

try
            {
                string poststring = String.Format("username={0}&password={1}&key={2}&hwid={3}", Username, Password, "272453745345934756392485764589", GetHardwareID());
                HttpWebRequest httpRequest =
    (HttpWebRequest)WebRequest.Create("mywebsite");

                httpRequest.Method = "POST";
                httpRequest.ContentType = "application/x-www-form-urlencoded";

                byte[] bytedata = Encoding.UTF8.GetBytes(poststring);
                httpRequest.ContentLength = bytedata.Length;

                Stream requestStream = httpRequest.GetRequestStream();
                requestStream.Write(bytedata, 0, bytedata.Length);
                requestStream.Close();


                HttpWebResponse httpWebResponse =
                (HttpWebResponse)httpRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();

                StringBuilder sb = new StringBuilder();

                using (StreamReader reader =
                new StreamReader(responseStream, System.Text.Encoding.UTF8))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        sb.Append(line);
                    }
                }

                return sb.ToString();
            }
            catch (Exception Error)
            {
                return Error.ToString();
            }
如果有人能帮助我,我将不胜感激。

最佳答案

根据 HttpWebRequest 文档

We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient class.

HttpClient 只包含异步 API,因为 Web 请求需要等待。在等待响应时卡住整个应用程序是不好的。
因此,这里有一些异步函数来使用 POST 发出 HttpClient 请求并向那里发送一些数据。
首先单独创建HttpClient because

HttpClient is intended to be instantiated once per application, rather than per-use.


private static readonly HttpClient client = new HttpClient();
然后实现方法。
private async Task<string> PostHTTPRequestAsync(string url, Dictionary<string, string> data)
{
    using (HttpContent formContent = new FormUrlEncodedContent(data))
    {
        using (HttpResponseMessage response = await client.PostAsync(url, formContent).ConfigureAwait(false))
        {
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        }
    }
}
或 C# 8.0
private async Task<string> PostHTTPRequestAsync(string url, Dictionary<string, string> data)
{
    using HttpContent formContent = new FormUrlEncodedContent(data);
    using HttpResponseMessage response = await client.PostAsync(url, formContent).ConfigureAwait(false);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
看起来比你的代码简单,对吧?
调用者异步方法看起来像
private async Task MyMethodAsync()
{
    Dictionary<string, string> postData = new Dictionary<string, string>();
    postData.Add("message", "Hello World!");
    try
    {
        string result = await PostHTTPRequestAsync("http://example.org", postData);
        Console.WriteLine(result);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
如果您不熟悉 async/awaitit's time to say Hello

关于c# - 如何在 C# 中发送带有表单数据的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62679718/

相关文章:

c# - 无法公开地址处的 WCF 端点

c# - C# 子表达式中 OR 的三元运算符用法

c# - Azure 存储队列 - 消息 ID

c# - 是否有可能捕获您无法处理的异常(在 C# 中)?

c# - Linq 实体 (EF 4.1) : How to do a SQL LIKE with a wildcard in the middle ( '%term%term%' )?

c# - View 模型在数据绑定(bind)之外的作用?

c# - 如何从列表集合中选择唯一列表?

c# - 即使在 CallBase = true/false 之后,原始方法仍然在 Moq 中被调用

c# - 将 x.y 转换为 a/b,其中 x.y = a/b c#

C#数组从一行中获取最后一项