c# - 如何在 C# 中发送带有表单数据的 POST
问题描述
我正在尝试制作一个程序,该程序使用用户名、密码、硬件 ID 和 POST 中的密钥请求我的网站。
我这里有这段代码,它应该使用该表单数据向我的网站发送一个 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
文档
我们不建议您
HttpWebRequest
用于新开发。相反,使用System.Net.Http.HttpClient
类。
HttpClient
仅包含异步 API,因为 Web 请求需要等待。在等待响应时冻结整个应用程序并不好。
因此,这里有一些异步函数来发出POST
请求HttpClient
并向那里发送一些数据。
首先,HttpClient
单独创建,因为
HttpClient
旨在为每个应用程序实例化一次,而不是每次使用。
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/await
,是时候打个招呼了。
推荐阅读
- python - 当我从进行所有内存学习切换到数据生成器时,为什么我的验证准确度会低很多?
- c# - 试图实现一个 C++ 库,需要一些关于如何与它交互的指针
- javascript - 警报在 Ajax 成功函数中不起作用
- graphql - 使用 GraphQL Mutation 插入多条记录
- azure-devops - 仅返回 OData 查询中相关实体的最新记录
- squid - OpenVPN 503 服务在 http 代理后面不可用
- google-sheets - 过滤数组 If Date >= Today()
- python - Pyspark 计算分组表上的字段
- powershell-core - 为什么 Import-Module 会在 AppData\Local\Temp 中创建 .psd1 和 .psm1 文件?
- geant4 - 为什么我的修改后的 Pol01 在批处理模式下运行适用于除左圆偏振光子之外的所有偏振光子状态?