ASP.NET/C# WebRequest POST Google OAuth API


這篇文章主要是分享一段代碼,解決的問題是:通過 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());
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM