2011-09-21 74 views
2

我遇到新發布的Google+ API的幾個問題來獲取的訪問令牌......訪問令牌的Google+

我一直在關注documentation,我有一個代碼(「4/blablabla」),但當我發送POST請求獲得一個訪問令牌,我得到一個「(400)錯誤的請求」的響應...

這裏是我的一段代碼:

// 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 ... 
+0

如果您使用Fiddler(或類似的)來捕獲引發400的請求,它看起來像什麼? – bzlm

+0

我沒有看到你的代碼有問題,它看起來像谷歌是因爲在FireFox和Google chrome中發出這個錯誤而聞名。如果他們有Google Plus開發者論壇,你可以嘗試請求一個答案。 – Keeano

+0

這個問題的標題是無用的 - 它不描述問題或提出問題 –

回答

2

您忘記了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,我今天問過並稍後解決。

+0

非常感謝它的工作! – Slyvain

1

授權使用Google+ API uses OAuth 2.0 。您似乎正在實施OAuth 2.0和OAuth 1.0的混合使用:您的代碼將爲OAuth 2.0請求計算OAuth 1.0 oauth_signature,該請求在OAuth 2.0中已過時。

看一看OAuth 2.0 specification draft,並嘗試完全按照Google's OAuth 2.0 documentation中的示例進行操作。或者僅使用支持OAuth 2.0的Google's .NET library

+0

真的!謝謝你指出,但這還不足以解決我的問題。我使用下面的e-MEE的代碼,它解決了它;) – Slyvain