新版Google+ API检索访问令牌时遇到一些问题...
我一直跟随documentation,我得到一个代码(“ 4 / blablabla”),但是当我发送POST请求以获取访问令牌时,我得到了一个“(400)Bad Request”响应...
这是我的代码:
// We have a request code, now we want an access token
StringBuilder authLink = new StringBuilder();
authLink.Append("https://accounts.google.com/o/oauth2/token");
authLink.AppendFormat("?code={0}", gplusCode);
authLink.AppendFormat("&client_id={0}", myClientId);
authLink.AppendFormat("&client_secret={0}", mySecret);
authLink.AppendFormat("&redirect_uri={0}", myRedirectUri);
authLink.Append("&scope=https://www.googleapis.com/auth/plus.me");
authLink.Append("&grant_type=authorization_code");
OAuthBase oAuth = new OAuthBase();
string normalizedUrl, normalizedRequestParameters;
string oAuthSignature = oAuth.GenerateSignature(new Uri(authLink.ToString()), appKey, appSecret, code, null, HttpMethod.POST.ToString(), oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedRequestParameters);
oAuthSignature = oAuth.UrlEncode(oAuthSignature);
// Rebuild query url with authorization
string url = string.Format("{0}?{1}&oauth_signature={2}", normalizedUrl, normalizedRequestParameters, oAuthSignature);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = HttpMethod.POST.ToString();
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0;
// Send the request and get the response
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do stuff ...
最佳答案
您忘记了POST请求。尝试这个:
string url = "https://accounts.google.com/o/oauth2/token";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
request.Method = HttpMethod.POST.ToString();
request.ContentType = "application/x-www-form-urlencoded";
// You mus do the POST request before getting any response
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(parameters); // parameters="code=...&client_id=...";
Stream os = null;
try // send the post
{
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do stuff ...
这将为您提供带有访问令牌的Json。此外,您还可以看到我今天问并稍后解决的my question。