c# HttpClient和HttpWebRequest添加Basic类型的Authentication认证

c#项目中用到调用客户接口,basic身份认证,base64格式加密(用户名:密码)贴上代码以备后用

1、使用HttpClient实现basic身份认证

using (HttpClient client = new HttpClient())
            {
                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;//返回值
            }

 

2、使用HttpWebRequest实现basic身份认证

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("接口地址");
            request.Method = "Post";
            request.CookieContainer = new CookieContainer();
            request.ContentType = "application/json;";

            (1)设置请求Credentials
            CredentialCache credentialCache = new CredentialCache();
            credentialCache.Add(new Uri("接口地址"),"Basic", new NetworkCredential("用户名", "密码"));
            request.Credentials = credentialCache;

            (2)设置Headers Authorization
            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();
                }
            }

 

https://www.cnblogs.com/forydb/p/10000301.html

转载于:https://www.cnblogs.com/tsql/p/11418064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值