使用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(Username,Password));
            request.Credentials = credentialCache;

            (2)设置Headers Authorization

            String authorization= Username+ ":"+Password;
            request.Headers.Add("Authorization", "Basic "+Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization)));
            using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string content = reader.ReadToEnd();
                }
            }

posted @ 2020-05-13 17:17  金虹巴巴  阅读(1155)  评论(0编辑  收藏  举报