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 "";
}
View Code

2调用

 var result = HttpClientPost("http://localhost:21021/api/values", accessToken);

posted @ 2019-12-12 13:36  沂水弦歌  阅读(3310)  评论(2编辑  收藏  举报