您的位置:首页 > 理论基础 > 计算机网络

HttpClient json格式访问api

2020-07-21 04:13 1231 查看

public static string HttpPostRequestAsync(string Url, string Api, object obj, string ContentType = “application/json”)
{
string result = “”;
try
{
using (System.Net.Http.HttpClient http = new System.Net.Http.HttpClient())
{
http.DefaultRequestHeaders.Add(“User-Agent”, @“Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)”);
http.DefaultRequestHeaders.Add(“Accept”, @“text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8”);
using (HttpContent content = new JsonContent(obj))
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(ContentType);
string url = string.Format("{0}{1}", Url, Api);
var response = http.PostAsync(url, content).Result;
System.IO.Stream myResponseStream = response.Content.ReadAsStreamAsync().Result;
System.IO.StreamReader myStreamReader = new System.IO.StreamReader(myResponseStream, System.Text.Encoding.GetEncoding(“utf-8”));
result = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
}
}
}
catch (Exception ex)
{
return new DBUtility.CBIUtility(ex.Message).ToString();
}
return result;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: