zoukankan      html  css  js  c++  java
  • HttpClient和HttpWebRequest添加Basic类型的Authentication认证

    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();
                    }
                }

    离神越近,感觉自己越渺小。
  • 相关阅读:
    业务逻辑层封装
    了解ASP.NET MVC几种ActionResult的本质:EmptyResult & ContentResult
    Facade外观模式
    了解ASP.NET MVC几种ActionResult的本质:FileResult
    示例代码浏览器5.4功能更新
    面试体验:Microsoft 篇
    Mono 2.11.3 发布包含微软的 Entity Framework
    系统架构设计师
    对数据访问层的抽象中
    说说项目中的插件思想
  • 原文地址:https://www.cnblogs.com/bo0214/p/12801049.html
Copyright © 2011-2022 走看看