我可以很好地获取访问密钥,但在尝试使用以下代码获取令牌时,我收到了(400)错误请求错误。我尝试了一切。我知道凭据是正确的,因为它们与Google API客户端配合使用。话虽这么说,我不能使用它,因为我需要这个在3.5框架中运行。这里有什么明显的错误吗?
private const string clientId = "1003120056405-ofafvc699hjujp0a9952g8vjaludk90j.apps.googleusercontent.com";
private const string clientSecret = "******************";
private string redirectURI = "urn:ietf:wg:oauth:2.0:oob:auto";
public static AuthResponse Exchange(string authCode, string clientid, string secret, string redirectURI){
try
{
var request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code&scope={4}", HttpUtility.UrlEncode(authCode), clientid, secret, redirectURI, "");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
MessageBox.Show(responseString);
return null;
}
catch (WebException ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
答案 0 :(得分:1)
我得到了这个工作。上面的代码很好,但我的accessKey被错误地转换为小写。密钥区分大小写以检查令牌。