AI智能
改变未来

HttpClient 访问中增 Authorization Bearer token 认证

public static string HttpPostToken(string Url, string Api, object obj, string token, 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”);
http.DefaultRequestHeaders.Add(“Authorization”, “Bearer \” + token);
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;
}

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » HttpClient 访问中增 Authorization Bearer token 认证