主要讲解常见的get请求和post请求
GET
var client = new HttpClient();
//3秒钟不响应就超时
client.Timeout=TimeSpan.FromSeconds(3);
using HttpResponseMessage response = await client.GetAsync("todos/3");
var jsonResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine($"{jsonResponse}\n");
POST
var client = new HttpClient();
var nowTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
client.DefaultRequestHeaders.Add("time",nowTimestamp);
//3秒钟不响应就超时
client.Timeout=TimeSpan.FromSeconds(3);
var param = new List<KeyValuePair<string, string>>();
param.Add(new KeyValuePair<string, string>("a", "xxxx"));
var response = await client.PostAsync(url, new FormUrlEncodedContent(param));
if (response.StatusCode == HttpStatusCode.OK)
{var jsonStr = await response.Content.ReadAsStringAsync();return JsonConvert.DeserializeObject<XXXObject>(jsonStr);
}var errorMsg = await response.Content.ReadAsStringAsync();
post其他请求只需要改变content内容即可
参考
https://www.cnblogs.com/xiaoxiaotank/p/16273773.html
https://github.com/tmenier/Flurl
https://learn.microsoft.com/zh-cn/dotnet/fundamentals/networking/http/httpclient
还是flurl用习惯了效率高一些