c# HttpClient和HttpWebRequest添加Basic类型的Authentication认证
2021-06-30 01:07
标签:接口 efault bre cat create odi work 认证 ddr c#项目中用到调用客户接口,basic身份认证,base64格式加密(用户名:密码)贴上代码以备后用 1、使用HttpClient实现basic身份认证 using (HttpClient client = new HttpClient()) 2、使用HttpWebRequest实现basic身份认证 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("接口地址"); (1)设置请求Credentials (2)设置Headers Authorization c# HttpClient和HttpWebRequest添加Basic类型的Authentication认证 标签:接口 efault bre cat create odi work 认证 ddr 原文地址:https://www.cnblogs.com/forydb/p/10000301.html
{
client.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}")));
HttpContent httpContent = new StringContent("", Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Uri address = new Uri("接口地址");
var response = client.PostAsync(address, httpContent).Result.Content.ReadAsStringAsync().Result;//返回值
}
request.Method = "Post";
request.CookieContainer = new CookieContainer();
request.ContentType = "application/json;";
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri("接口地址"),"Basic", new NetworkCredential("bayer_rx", "bayerClientSecret"));
request.Credentials = credentialCache;
request.Headers.Add("Authorization", "Basic "+Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}")));
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string content = reader.ReadToEnd();
}
}
文章标题:c# HttpClient和HttpWebRequest添加Basic类型的Authentication认证
文章链接:http://soscw.com/essay/99627.html