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.
精彩评论