2012-11-18 111 views
4

我試圖找回OAuth訪問令牌才能在asp.net mvc的一些谷歌API的調用,我寫了一個動作下面的代碼:谷歌API的OAuth訪問令牌檢索 - 400錯誤的請求

 public ActionResult GetOAuthToken() 
     { 

     String url = "https://accounts.google.com/o/oauth2/token"; 

     // Create a request using a URL that can receive a post. 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
     // Set the Method property of the request to POST. 
     request.Method = "POST"; 
     request.Host = "accounts.google.com"; 
     // Create POST data and convert it to a byte array. 
     string postData = String.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"].ToString(), OAuthConfig.client_id, OAuthConfig.client_secret, OAuthConfig.token_redirect_uri); 
     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] byteArray = encoding.GetBytes(postData); 
     // Set the ContentType property of the WebRequest. 
     request.ContentType = "application/x-www-form-urlencoded"; 
     // Set the ContentLength property of the WebRequest. 
     request.ContentLength = byteArray.Length; 
     // Get the request stream. 
     Stream dataStream = request.GetRequestStream(); 

     // Write the data to the request stream. 
     dataStream.Write(byteArray, 0, byteArray.Length); 
     // Close the Stream object. 
     dataStream.Close(); 
     // Get the response. 
     WebResponse response = request.GetResponse(); 

     // SOME CODE TO PROCESS THE RESPONSE 

     Response.Redirect("/Home"); 
     return View(); 
     } 

的OAuthConfig只是包含客戶端ID類,客戶端密鑰等

我不斷收到「遠程服務器返回錯誤:(400)錯誤的請求」。在request.GetResponse()行。我哪裏錯了?

+0

是否有響應正文?它說什麼? – spender

+0

沒有。線request.GetResponse() –

+0

拋出異常幾乎肯定是。捕獲WebException並檢出其屬性。 http://msdn.microsoft.com/en-us/library/system.net.webexception.response.aspx – spender

回答

1

谷歌確實提供了一個更高層次的庫來處理它的服務,這處理了url的格式,我發現它使得它更容易使用它的apis。請參閱http://code.google.com/p/google-api-dotnet-client/

+1

我嘗試過使用.net庫,但是如果您已經擁有授權碼,沒有任何關於如何簡單獲取訪問令牌的明確教程。我在這裏看到了示例代碼:http://code.google.com/p/google-api-dotnet-client/wiki/OAuth2,但它是在簡單的客戶端應用程序的上下文中。我不知道如何翻譯我的場景中的代碼,我在授權碼中查詢字符串。 –

相關問題