2012-03-09 56 views
0

從谷歌獲得用於訪問用戶的日曆的授權代碼,我現在試圖交換這個訪問令牌。根據自己的文檔:谷歌日曆API - 錯誤的請求(400)試圖交換代碼訪問令牌

實際要求可能看起來像:

POST /o/oauth2/token HTTP/1.1 
Host: accounts.google.com 
Content-Type: application/x-www-form-urlencoded 

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu& 
client_id=8819981768.apps.googleusercontent.com& 
client_secret={client_secret}& 
redirect_uri=https://oauth2-login-demo.appspot.com/code& 
grant_type=authorization_code 

我嘗試訪問此如下(C#):

string url = "https://accounts.google.com/o/oauth2/token"; 
WebRequest request = HttpWebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 

string body = "code=<the_code_I_received>&\r\n" 
    + "client_id=<my_client_id>&\r\n" 
    + "client_secret=<my_client_secret>&\r\n" 
    + "redirect_uri=http://localhost:4300\r\n" 
    + "grant_type=authorization_code&\r\n" 
          ; 
byte[] bodyBytes = Encoding.ASCII.GetBytes(body); 
request.ContentLength = bodyBytes.Length ; 
Stream bodyStream = request.GetRequestStream(); 
bodyStream.Write(bodyBytes, 0, bodyBytes.Length); 
bodyStream.Close(); 

try 
{ 
    request.GetResponse(); 

的「http: // localhost:4300'與我原來的請求完全一樣(並且它是有效的,因爲我通過在該端口上作爲web服務器進行偵聽而返回代碼),但我也嘗試了'http:// localhost '只是 以防萬一。

我嘗試了一些建議,如將代理設置爲空(不更改)並更改接受(不允許將該標頭添加到Web請求)。

在每一種情況下,我都會收到HTTP 400-錯誤的請求(try/catch觸發一個異常聲明)。

在/ token(我會嘗試任何東西!)後面加一個斜槓導致500內部服務器錯誤,所以也不是這樣。

任何想法我做錯了什麼?

回答

0

您是否需要體內的新線\ r \ n?此代碼適用於我...

var req0 = WebRequest.Create("https://accounts.google.com/o/oauth2/token"); 
req0.Method = "POST"; 
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", 
code, //the code i got back 
"2xxx61.apps.googleusercontent.com", "XJxxxFy", 
"http://localhost:1599/home/oauth2callback"); //my return URI 

byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
req0.ContentType = "application/x-www-form-urlencoded"; 
req0.ContentLength = byteArray.Length; 
using (Stream dataStream = req0.GetRequestStream()) 
{ 
    dataStream.Write(byteArray, 0, byteArray.Length); 
    dataStream.Close(); 
} 
try 
{ 
using (WebResponse response = req0.GetResponse()) 
    { 
    using (var dataStream = response.GetResponseStream()) 
     {  
     using (StreamReader reader = new StreamReader(dataStream)) 
     { 
     string responseFromServer = reader.ReadToEnd(); 
     var ser = new JavaScriptSerializer(); 
      accessToken = ser.DeserializeObject(responseFromServer); 
     } 
    } 
} 
} 
catch (WebException wex){ var x = wex; } 
catch (Exception ex){var x = ex;} 
相關問題