這篇文章主要是分享一段代碼,解決的問題是:通過 WebRequest 向 https://accounts.google.com/o/oauth2/token 發起 HTTP POST 請求,根據 authorization code 獲取 access_token。
C#代碼如下:
public ActionResult GoogleOAuthCallback() { var webRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token") as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; var postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", Request.QueryString["code"], "Client ID", "Client secret", "Redirect URIs"); using(var sw = new StreamWriter(webRequest.GetRequestStream())) { sw.Write(postData); } using (var response = webRequest.GetResponse()) { using (var sr = new StreamReader(response.GetResponseStream())) { return Content(sr.ReadToEnd()); } } }