今天进行EMQ http api调用的时候遇到一个问题,一直弹出登录验证框
在官网资料中也找不到相关的接口,如下图:
以前也经常看到这种登录,不过我这里没有用程序去调用过这样类似的接口.
后来我想到经常在用迅雷下载一些电影的时候,在迅雷地址中看到过一种ftp的写法,如: ftp:账号:密码@xxx.com/xyz.mp4如此如此.
我就尝试了一下账号密码登录,居然成功了.
这样一来我百度的范围就缩小了,找到了一个关键词 -----> HTTP Authorization
原来是这玩意搞的鬼
记录一下分享给大家.
以下内容来自网络:https://www.cnblogs.com/forydb/p/10000301.html
c#项目中用到调用客户接口,basic身份认证,base64格式加密(用户名:密码)贴上代码以备后用
1、使用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 }
2、使用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 Authorization12 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 }