简体   繁体   English

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

[英]How to send POST with form data in C#

I am trying to make a program that requests my website with a username, password, hardware ID and a key in POST.我正在尝试制作一个程序,该程序使用用户名、密码、硬件 ID 和 POST 中的密钥请求我的网站。

I have this code here that should send a POST request to my website with that form data, but when it sends, my webserver reports back that it didn't recieve the POST data我这里有这段代码,它应该使用该表单数据向我的网站发送 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();
            }

If someone could help me, I would really appreciate it.如果有人可以帮助我,我将不胜感激。

As per HttpWebRequest documentation根据HttpWebRequest文档

We don't recommend that you use HttpWebRequest for new development.我们不建议您使用HttpWebRequest进行新开发。 Instead, use the System.Net.Http.HttpClient class.而是使用System.Net.Http.HttpClient class。

HttpClient contains only asynchronous API because Web requests needs awaiting. HttpClient仅包含异步 API 因为 Web 请求需要等待。 That's not good to freeze entire Application while it's pending response.在等待响应时冻结整个应用程序并不好。

Thus, here's some async function to make POST request with HttpClient and send there some data.因此,这里有一些异步 function 使用HttpClient发出POST请求并发送一些数据。

First of all, create HttpClient seperately because首先,单独创建HttpClient因为

HttpClient is intended to be instantiated once per application, rather than per-use. HttpClient旨在为每个应用程序实例化一次,而不是每次使用。

private static readonly HttpClient client = new HttpClient();

Then implement the method.然后实现方法。

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);
        }
    }
}

Or C# 8.0或 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);
}

Looks easier than your code, right?看起来比你的代码更容易,对吧?

Caller async method will look like调用者异步方法看起来像

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);
    }
}

If you're not familiar with async/await , it's time to say Hello .如果你不熟悉async/await是时候说 Hello 了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM