开发者

Failed To get oauth2 Token via request.GetResponse()

开发者 https://www.devze.com 2023-03-20 12:52 出处:网络
I\'m Trying to access Google Data (Contact, Edit profile data, Calendar ... etc) by using GData and OAuth2.0 server side (Check this link), I finished the first step and got the first code, and when t

I'm Trying to access Google Data (Contact, Edit profile data, Calendar ... etc) by using GData and OAuth2.0 server side (Check this link), I finished the first step and got the first code, and when try to post a request to get the oauth2_token I always got the error "The remote server returned an error: (400) Bad 开发者_JAVA技巧Request." Here is the code I use to POST the request that returns the 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();

Any help??? I spent 2 days till now trying to solve it but in vain :(


could it be that the redirect_uri needs to be URI encoded?

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


I think you should encode the redirect_uri parameter using HttpUtility.UrlEncode.

also, you should encode the request body using Utf8 encoding:

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

hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消