OAuth 2.0注意事项
1、 获取access_token时,请使用POST

  private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password); return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
}
   /// <summary>
/// 获取Token
/// </summary>
/// <returns></returns>
private static string OAuthClientCredentialsToken()
{
const string clientId = "";
const string clientSecret = "";
string result = string.Empty; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(_baseUrl + "/token");
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Accept = "application/json";
httpWebRequest.Timeout = ;
httpWebRequest.KeepAlive = false;
httpWebRequest.AllowAutoRedirect = true;
// httpWebRequest.Headers.Add("Accept-Language", "zh-cn");
// httpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
// httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
httpWebRequest.Headers.Add("Authorization", GetAuthorization(clientId, clientSecret));
//Credentials
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
//post参数
StringBuilder postParam = new StringBuilder();
Dictionary<string, string> parameters = new Dictionary<string, string> { { "grant_type", "client_credentials" } };
int i = ;
foreach (KeyValuePair<string, string> parameter in parameters)
{
if (i > )
postParam.Append("&");
postParam.AppendFormat("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value));
i++;
} byte[] postData = Encoding.UTF8.GetBytes(postParam.ToString());
httpWebRequest.ContentLength = postData.Length; try
{
Stream requesStream = httpWebRequest.GetRequestStream();
requesStream.Write(postData, , postData.Length);
requesStream.Close(); WebResponse response = httpWebRequest.GetResponse();
Stream stream = response.GetResponseStream();
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
reader.Close();
}
stream.Close();
}
}
catch (WebException ex)
{
throw new Exception(ex.Message);
}
return !string.IsNullOrWhiteSpace(result) ? JObject.Parse(result)["access_token"].Value<string>() : result;
}

2、 访问需要授权的Api,请使用http/https协议,并且加上access token的Header
3 、Header格式为"Authorization: Bearer access_token",其中Bearer后面有一个空格

  /// <summary>
/// HttpGet
/// </summary>
/// <param name="url"></param>
/// <param name="token"></param>
/// <param name="contentType"></param>
/// <returns></returns>
private static string HttpGet(string url, string token, string contentType = "application/x-www-form-urlencoded")
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.ContentType = contentType;
httpWebRequest.Accept = "application/json";
httpWebRequest.Timeout = ;
httpWebRequest.AllowAutoRedirect = false;
//Bearer+空格
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
httpWebRequest.Credentials = CredentialCache.DefaultCredentials; string result = null;
try
{
WebResponse response = httpWebRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
{
result = streamReader.ReadToEnd();
streamReader.Close();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return result;
}

最新文章

  1. 遇到bug怎么办
  2. Windows上安装Maven
  3. Spring基于注解及SpringMVC
  4. How to Iterate Map
  5. hust-1024-dance party(最大流--枚举,可行流判断)
  6. C#基础学习心得(一)
  7. qq去广告
  8. HPQC HP Quality Center windows 服务
  9. springMVC源码分析--拦截器HandlerExecutionChain(三)
  10. JavaScript 浏览器中的事件
  11. Java API使用
  12. AVPass技术分析:银行劫持类病毒鼻祖BankBot再度来袭,如何绕过谷歌play的杀毒引擎?
  13. str
  14. CALayer-CAShapeLayer/CAGradientLayer
  15. delphi Format格式化函数
  16. hdu 4521 小明系列问题——小明序列 线段树+二分
  17. 深入浅出java IO模型
  18. mysql性能优化之索引优化
  19. 老男孩Day4作业:员工信息查询系统
  20. Java微信小程序开发_00_资源帖

热门文章

  1. mysql 开发进阶篇系列 8 锁问题 (共享锁与排它锁演示)
  2. 微信小程序使用wxParse解析html
  3. 重学python
  4. 支付宝PC端单笔支付同步回调session失效问题
  5. C#系列之聊聊.Net Core的InMemoryCache
  6. VS Code 安装 C++ 调试环境
  7. MySQL:进阶之视图函数
  8. React Native 入门基础知识总结
  9. vue_drf之多级过滤、排序、分页
  10. 类似aaa?a=1&amp;b=2&amp;c=3&amp;d=4,如何将问号以后的数据变为键值对