zoukankan      html  css  js  c++  java
  • 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();
                    }
                }

  • 相关阅读:
    Java IO流学习总结
    wpf 右键ListBox可编辑
    silverlight 独立存储之路径、保存图片、扩展空间注意事项
    自定义wpf的MessageBox(可重定义button键文字)
    细数各大顶级网站的垃圾设置!!!
    无法为 SSL/TLS 安全通道与颁发机构“*****”建立信任关系。
    JS完美运动框架
    修改thinkphp缩略图源码 生成固定的缩略图
    20120609 随笔
    php 图片处理函数
  • 原文地址:https://www.cnblogs.com/forydb/p/10000301.html
Copyright © 2011-2022 走看看