简单的C# POST请求工具类,可以使用它来发送POST请求并获取响应
#工具类
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class PostRequestHelper
{
private readonly HttpClient _httpClient;
public PostRequestHelper()
{
_httpClient = new HttpClient();
}
public async Task<string> SendPostRequestAsync(string url, object data)
{
var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
使用示例
private async void POSTexample(){
var postRequestHelper = new PostRequestHelper();
string response = await postRequestHelper.SendPostRequestAsync("http://example.com/api/endpoint", new { foo = "bar" });
MessageBox.Show(response);
}
在上面的示例中,我们创建了一个PostRequestHelper实例并使用SendPostRequestAsync方法发送了一个POST请求到http://example.com/api/endpoint,并将一个包含foo属性的简单数据对象作为请求正文发送。该方法返回一个包含响应正文的字符串的Task对象。