HttpWebRequest 请求带OAuth2 授权的webapi

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;
}
上一篇:【Gym 100971K】Palindromization


下一篇:ZOJ 3820 Building Fire Stations