我試圖找回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()行。我哪裏錯了?
是否有響應正文?它說什麼? – spender
沒有。線request.GetResponse() –
拋出異常幾乎肯定是。捕獲WebException並檢出其屬性。 http://msdn.microsoft.com/en-us/library/system.net.webexception.response.aspx – spender