NETCore HttpClient 以Post方式调用外部API
1使用HttpClient的PostAsync方法发送Json数据请求
public static string HttpClientPost(string url, object datajson) { HttpClient httpClient = new HttpClient();//http对象 //表头参数 httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //转为链接需要的格式 HttpContent httpContent = new JsonContent(datajson); //请求 HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<string> t = response.Content.ReadAsStringAsync(); if (t != null) { return t.Result; } } return ""; }
2调用
var result = HttpClientPost("http://localhost:21021/api/values", accessToken);