在.NET中发送HTTP POST请求

在.NET中发送HTTP POST请求

技术背景

在.NET开发中,经常需要与外部服务进行交互,发送HTTP POST请求是常见的需求之一。例如,向服务器提交表单数据、调用API接口等。不同的.NET版本和场景下,有多种方式可以实现HTTP POST请求。

实现步骤

方法A:HttpClient(推荐)

  1. 适用范围:.NET Framework 4.5+、.NET Standard 1.1+ 和 .NET Core 1.0+。
  2. 设置:建议在应用程序的生命周期内实例化一个 HttpClient 并共享它。
1
2
3
using System.Net.Http;

private static readonly HttpClient client = new HttpClient();
  1. POST请求示例
1
2
3
4
5
6
7
8
9
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};

var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();

方法B:第三方库

RestSharp

1
2
3
4
5
6
7
8
9
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string

Flurl.Http

1
2
3
4
5
using Flurl.Http;

var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();

方法C:HttpWebRequest(不推荐用于新开发)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

方法D:WebClient(不推荐用于新开发)

1
2
3
4
5
6
7
8
9
10
11
12
using System.Net;
using System.Collections.Specialized;

using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";

var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}

核心代码

通用的HttpClient POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
using System.Net.Http;

private static readonly HttpClient client = new HttpClient();

var values = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};

var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://example.com/api", content);
var responseString = await response.Content.ReadAsStringAsync();

发送JSON数据的POST请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace ConsoleApplication1
{
class Customer
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

public class Program
{
private static readonly HttpClient _Client = new HttpClient();
private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();

static async Task Run()
{
string url = "http://www.example.com/api/Customer";
Customer cust = new Customer() { Name = "Example Customer", Address = "Some example address", Phone = "Some phone number" };
var json = _Serializer.Serialize(cust);
var response = await Request(HttpMethod.Post, url, json, new Dictionary<string, string>());
string responseText = await response.Content.ReadAsStringAsync();
}

static async Task<HttpResponseMessage> Request(HttpMethod pMethod, string pUrl, string pJsonContent, Dictionary<string, string> pHeaders)
{
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = pMethod;
httpRequestMessage.RequestUri = new Uri(pUrl);
foreach (var head in pHeaders)
{
httpRequestMessage.Headers.Add(head.Key, head.Value);
}
switch (pMethod.Method)
{
case "POST":
HttpContent httpContent = new StringContent(pJsonContent, Encoding.UTF8, "application/json");
httpRequestMessage.Content = httpContent;
break;
}

return await _Client.SendAsync(httpRequestMessage);
}
}
}

最佳实践

  1. 使用 HttpClient:在大多数情况下,推荐使用 HttpClient,它是异步且高性能的。
  2. 避免频繁创建 HttpClient:建议在应用程序的生命周期内实例化一个 HttpClient 并共享它。
  3. 错误处理:在发送请求时,要进行适当的错误处理,捕获可能的异常。
  4. 使用 HttpClientFactory:对于依赖注入的场景,可以使用 HttpClientFactory

常见问题

  1. HttpClient 超时问题:可以通过设置 HttpClientTimeout 属性来解决。
1
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
  1. 请求被阻止:可能是网络问题或服务器配置问题,检查网络连接和服务器设置。
  2. JSON 序列化和反序列化问题:确保使用正确的 JSON 序列化和反序列化方法,如 System.Text.JsonNewtonsoft.Json

在.NET中发送HTTP POST请求
https://119291.xyz/posts/send-http-post-request-in-dotnet/
作者
ww
发布于
2025年6月20日
许可协议