无法通过request.GetResponse()获取oauth2令牌

时间:2011-07-13 13:45:58

标签: c# asp.net gdata-api oauth-2.0

我正在尝试使用GData和OAuth2.0服务器端(Check this link)访问Google数据(联系人,编辑个人资料数据,日历等),我完成了第一步并获得了第一个代码,当尝试发布请求以获取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 个答案:

答案 0 :(得分:1)

可能是redirect_uri需要进行URI编码吗?

[https://groups.google.com/forum/#!topic/oauth2-dev/9xnn8nUIA2s]

答案 1 :(得分:1)

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

另外,您应该使用Utf8编码对请求正文进行编码:

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

希望这会有所帮助。

相关问题