今天进行EMQ http api调用的时候遇到一个问题,一直弹出登陆验证框html
在官网资料中也找不到相关的接口,以下图:json
之前也常常看到这种登陆,不过我这里没有用程序去调用过这样相似的接口.c#
后来我想到常常在用迅雷下载一些电影的时候,在迅雷地址中看到过一种ftp的写法,如: ftp:帐号:密码@xxx.com/xyz.mp4如此如此.api
我就尝试了一下帐号密码登陆,竟然成功了.网络
这样一来我百度的范围就缩小了,找到了一个关键词 -----> HTTP Authorizationapp
原来是这玩意搞的鬼ide
记录一下分享给你们.加密
如下内容来自网络:https://www.cnblogs.com/forydb/p/10000301.htmlspa
c#项目中用到调用客户接口,basic身份认证,base64格式加密(用户名:密码)贴上代码以备后用code
一、使用HttpClient实现basic身份认证
1 using (HttpClient client = new HttpClient()) 2 { 3 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))); 4 HttpContent httpContent = new StringContent("", Encoding.UTF8); 5 httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 6 Uri address = new Uri("接口地址"); 7 var response = client.PostAsync(address, httpContent).Result.Content.ReadAsStringAsync().Result;//返回值 8 }
二、使用HttpWebRequest实现basic身份认证
1 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("接口地址"); 2 request.Method = "Post"; 3 request.CookieContainer = new CookieContainer(); 4 request.ContentType = "application/json;"; 5 6 //(1)设置请求Credentials 7 CredentialCache credentialCache = new CredentialCache(); 8 credentialCache.Add(new Uri("接口地址"), "Basic", new NetworkCredential("用户名", "密码")); 9 request.Credentials = credentialCache; 10 11 //(2)设置Headers Authorization 12 request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))); 13 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 14 { 15 using (StreamReader reader = new StreamReader(response.GetResponseStream())) 16 { 17 string content = reader.ReadToEnd(); 18 } 19 }