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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM