HttpWebRequest 请求带OAuth2 授权的webapi
2018-06-22 06:15:26来源:未知 阅读 ()
OAuth 2.0注意事项:
1、 获取access_token时,请使用POST
1 private static string GetAuthorization(string username, string password) 2 { 3 string authorization = string.Format("{0}:{1}", username, password); 4 5 return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization)); 6 }
1 /// <summary> 2 /// 获取Token 3 /// </summary> 4 /// <returns></returns> 5 private static string OAuthClientCredentialsToken() 6 { 7 const string clientId = "8518"; 8 const string clientSecret = "8518"; 9 string result = string.Empty; 10 11 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_baseUrl + "/token"); 12 httpWebRequest.Method = "POST"; 13 httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 14 httpWebRequest.Accept = "application/json"; 15 httpWebRequest.Timeout = 15000; 16 httpWebRequest.KeepAlive = false; 17 httpWebRequest.AllowAutoRedirect = true; 18 // httpWebRequest.Headers.Add("Accept-Language", "zh-cn"); 19 // httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); 20 // httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)"; 21 httpWebRequest.Headers.Add("Authorization", GetAuthorization(clientId, clientSecret)); 22 //Credentials 23 httpWebRequest.Credentials = CredentialCache.DefaultCredentials; 24 //post参数 25 StringBuilder postParam = new StringBuilder(); 26 Dictionary<string, string> parameters = new Dictionary<string, string> { { "grant_type", "client_credentials" } }; 27 int i = 0; 28 foreach (KeyValuePair<string, string> parameter in parameters) 29 { 30 if (i > 0) 31 postParam.Append("&"); 32 postParam.AppendFormat("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)); 33 i++; 34 } 35 36 byte[] postData = Encoding.UTF8.GetBytes(postParam.ToString()); 37 httpWebRequest.ContentLength = postData.Length; 38 39 try 40 { 41 Stream requesStream = httpWebRequest.GetRequestStream(); 42 requesStream.Write(postData, 0, postData.Length); 43 requesStream.Close(); 44 45 WebResponse response = httpWebRequest.GetResponse(); 46 Stream stream = response.GetResponseStream(); 47 if (stream != null) 48 { 49 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 50 { 51 result = reader.ReadToEnd(); 52 reader.Close(); 53 } 54 stream.Close(); 55 } 56 } 57 catch (WebException ex) 58 { 59 throw new Exception(ex.Message); 60 } 61 return !string.IsNullOrWhiteSpace(result) ? JObject.Parse(result)["access_token"].Value<string>() : result; 62 }
2、 访问需要授权的Api,请使用http/https协议,并且加上access token的Header
3 、Header格式为"Authorization: Bearer access_token",其中Bearer后面有一个空格
1 /// <summary> 2 /// HttpGet 3 /// </summary> 4 /// <param name="url"></param> 5 /// <param name="token"></param> 6 /// <param name="contentType"></param> 7 /// <returns></returns> 8 private static string HttpGet(string url, string token, string contentType = "application/x-www-form-urlencoded") 9 { 10 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 11 httpWebRequest.Method = "GET"; 12 httpWebRequest.ContentType = contentType; 13 httpWebRequest.Accept = "application/json"; 14 httpWebRequest.Timeout = 15000; 15 httpWebRequest.AllowAutoRedirect = false; 16 //Bearer+空格 17 httpWebRequest.Headers.Add("Authorization", "Bearer " + token); 18 httpWebRequest.Credentials = CredentialCache.DefaultCredentials; 19 20 string result = null; 21 try 22 { 23 WebResponse response = httpWebRequest.GetResponse(); 24 Stream responseStream = response.GetResponseStream(); 25 if (responseStream != null) 26 { 27 using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8)) 28 { 29 result = streamReader.ReadToEnd(); 30 streamReader.Close(); 31 } 32 } 33 } 34 catch (Exception ex) 35 { 36 throw new Exception(ex.Message); 37 } 38 return result; 39 }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- MVC 5限制所有HTTP请求必须是POST方式 2020-03-14
- ASP.NET页面请求超时时间设置多种方法 2019-11-19
- .net mvc超过了最大请求长度的解决方法 2019-08-09
- IIS下网站对options请求直接返回404 2019-05-13
- 第40章 自定义令牌请求验证和发布 2019-04-28
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash