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