要在.NET Framework 4.5中进行外部API的POST请求,你可以使用HttpClient类。文章来源:https://www.toymoban.com/news/detail-632267.html
1. Post请求
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
try
{
// 创建请求的内容
var requestData = new { Name = "John", Age = 30 };
var content = new StringContent(JsonConvert.SerializeObject(requestData), System.Text.Encoding.UTF8, "application/json");
// 发起POST请求并获取响应
HttpResponseMessage response = await client.PostAsync("https://api.example.com/some-endpoint", content);
// 确认请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
// 处理响应数据
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
// 处理请求异常
Console.WriteLine($"请求异常: {e.Message}");
}
}
}
}
另外,post传参还有另外一种方式,使用FormUrlEncodedContent
:文章来源地址https://www.toymoban.com/news/detail-632267.html
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"empid", "E01930"},
});
2. Get请求
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
// 设置API的URL
string apiUrl = "https://api.example.com/some-endpoint";
string fullUrl = apiUrl + "?emp=" + "A00001";
try
{
// 发送POST请求并获取响应
// HttpResponseMessage response = client.PostAsync(apiUrl, content).Result;
HttpResponseMessage response = client.GetAsync(fullUrl).Result;
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = response.Content.ReadAsStringAsync().Result;
// 处理响应数据
Console.WriteLine(responseBody);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
3. 奇葩(post请求url传参)
// 创建一个HttpClient实例
using (HttpClient client = new HttpClient())
{
// 设置API的URL
string apiUrl = "https://api.example.com/some-endpoint";
string fullUrl = apiUrl + "?emp=" + "A00001";
// 构造要发送的参数
var postData = new Dictionary<string, string>
{
{ "emp", "A00001" },
};
// 将参数转换为表单编码格式
var content = new FormUrlEncodedContent(postData);
try
{
// 发送POST请求并获取响应
// HttpResponseMessage response = client.PostAsync(apiUrl, content).Result;
HttpResponseMessage response = client.PostAsync(fullUrl,content).Result;
// 确保请求成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = response.Content.ReadAsStringAsync().Result;
// 处理响应数据
Console.WriteLine(responseBody);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
到了这里,关于.Net Framework请求外部Api的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!