1

我想设置谷歌分析API应用程序使用OAuth2离线访问,我用ASP.NET来发布我的授权代码换取刷新令牌,但我无法从服务器得到刷新令牌的响应。谷歌分析API - 检索与OAuth2和ASP.NET的刷新令牌

我已经使用了MSDN文档中的示例代码来发布发布请求,所以我只能假定这是正确的,但是我收到了错误消息“远程服务器返回错误:(400) .Net.HttpWebRequest.GetResponse()“:

using System; 
using System.IO; 
using System.Net; 
using System.Text; 

WebRequest request = WebRequest.Create ("https://accounts.google.com/o/oauth2/token?code=xxxmyauthorizationcodexxx&client_id=xxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxx&redirect_uri=https://mysite.com/oauth2callback&grant_type=authorization_code"); 
request.Method = "POST"; 
string postData = "code=xxxmyauthorizationcodexxx&client_id=xxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxx&redirect_uri=https://mysite.com/oauth2callback&grant_type=authorization_code"; 
byte[] byteArray = Encoding.UTF8.GetBytes (postData); 
request.ContentType = "application/x-www-form-urlencoded"; 
request.ContentLength = byteArray.Length; 

Stream dataStream = request.GetRequestStream(); 
dataStream.Write (byteArray, 0, byteArray.Length); 
dataStream.Close(); 

WebResponse response = request.GetResponse(); 
dataStream = response.GetResponseStream(); 
StreamReader reader = new StreamReader (dataStream); 
string responseFromServer = reader.ReadToEnd(); 

reader.Close(); 
dataStream.Close(); 
response.Close(); 

我已经成功地使用GET方法来获取授权码开始,我下面这个文档:https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse

我也使用https网站发出请求,我手动刷新我的授权码过期。有没有人有这个问题的解决方案?

编辑:对于任何遇到同样问题的人,首先查看下面的aeijdenberg的回复,但我的解决方案是,我用于代码参数的授权码相当即时过期 - 我一直刷新我的页面,而没有请求一个新的。获取数据只是显示responseFromServer变量的内容。

+0

谢谢你帮我:) – user1926138

回答

3

看起来你传递了两次参数。一旦查询字符串:

WebRequest request = WebRequest.Create ("https://accounts.google.com/o/oauth2/token?code=xxxx... 

然后再作为POST数据。我建议删除查询字符串,例如直接POST到“https://accounts.google.com/o/oauth2/token”。

也暗示保证,如果你没有这样做,所有的参数都是URL编码: http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx

+0

感谢你为这个,这帮助我得到我需要的东西! – mmmoustache

+0

谢谢你的解决方案。 – user1926138