通过request.GetResponse()获取oauth2 Token失败

本文关键字:oauth2 Token 失败 获取 request GetResponse 通过 | 更新日期: 2023-09-27 18:02:35

我正在尝试访问谷歌数据(联系人,编辑个人资料数据,日历…等)通过使用GData和OAuth2.0服务器端(检查此链接),我完成了第一步并获得了第一个代码,当尝试发布请求以获得oauth2_token时,我总是得到错误"远程服务器返回一个错误:(400)错误请求。"下面是我用来POST返回OAuth2_token的请求的代码:

string clientToken = Request.QueryString["code"];

        string post =
            string.Format(
                @"code={0}&client_id={1}&client_secret={2}&redirect_uri=http://localhost/default.aspx&grant_type=authorization_code",
                clientToken, Settings.ClientId, Settings.ClientSecret);
        WebRequest httpRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";
        StreamWriter streamWriter = new StreamWriter(httpRequest.GetRequestStream());
        streamWriter.Write(post);
        streamWriter.Flush();
        streamWriter.Close();
        var ss = (HttpWebResponse)httpRequest.GetResponse();
        Stream stream = ss.GetResponseStream();

帮忙吗? ?我花了2天直到现在试图解决它,但徒劳无功:(

通过request.GetResponse()获取oauth2 Token失败

可能是redirect_uri需要URI编码吗?

[https://groups.google.com/forum/# !主题/oauth2-dev/9 xnn8nuia2s]

我认为您应该使用HttpUtility.UrlEncode编码redirect_uri参数。

还应该使用Utf8编码对请求正文进行编码:

byte[] encoded = Encoding.UTF8.GetBytes(post);
httpRequest.ContentLength = encoded.Length