asp.net core使用httpclient

作者 : admin 本文共1302个字,预计阅读时间需要4分钟 发布时间: 2024-06-10 共1人阅读

主要讲解常见的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}
");

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内容即可
asp.net core使用httpclient插图

asp.net core中使用

//注入
services.AddHttpClient();
//构造函数使用
private readonly IHttpClientFactory _httpClientFactory;
public ValuesController(IHttpClientFactory httpClientFactory)
{
    _httpClientFactory = httpClientFactory;
}

参考

http://www.cnblogs.com/xiaoxiaotank/p/16273773.html
http://github.com/tmenier/Flurl
http://learn.microsoft.com/zh-cn/dotnet/fundamentals/networking/http/httpclient
http://www.cnblogs.com/willick/p/net-core-httpclient.html

还是flurl用习惯了效率高一些

本站无任何商业行为
个人在线分享-虚灵IT资料分享 » asp.net core使用httpclient
E-->