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());
        }
    }
}
posted @ 2012-04-28 22:29  dudu  阅读(4613)  评论(4编辑  收藏  举报