从Google获取授权代码以访问用户的日历后,我现在正尝试将其替换为访问令牌。根据自己的文档:
实际请求可能如下所示:
POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu& client_id=8819981768.apps.googleusercontent.com& client_secret={client_secret}& redirect_uri=https://oauth2-login-demo.appspot.com/code& grant_type=authorization_code
我尝试访问它的方法如下(C#):
string url = "https://accounts.google.com/o/oauth2/token";
WebRequest request = HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string body = "code=<the_code_I_received>&\r\n"
+ "client_id=<my_client_id>&\r\n"
+ "client_secret=<my_client_secret>&\r\n"
+ "redirect_uri=http://localhost:4300\r\n"
+ "grant_type=authorization_code&\r\n"
;
byte[] bodyBytes = Encoding.ASCII.GetBytes(body);
request.ContentLength = bodyBytes.Length ;
Stream bodyStream = request.GetRequestStream();
bodyStream.Write(bodyBytes, 0, bodyBytes.Length);
bodyStream.Close();
try
{
request.GetResponse();
'http:// localhost:4300'与我在原始请求中完全相同(并且它是有效的,因为我通过在该端口上监听作为Web服务器获得了代码),但我也试过了'http:// localhost'以防万一。
我尝试了一些建议,例如将代理设置为null(无更改)和更改Accept(不允许将该标头添加到Web请求)。
在每种情况下,我都会收到HTTP 400 - 错误的请求(try / catch会触发,并显示异常)。
在/ token之后设置一个斜杠(我会尝试任何东西!)导致500内部服务器错误,所以它也不是。
知道我做错了什么吗?
答案 0 :(得分:0)
你需要身体中的新线\ r \ n吗?这段代码对我有用......
var req0 = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
req0.Method = "POST";
string postData = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",
code, //the code i got back
"2xxx61.apps.googleusercontent.com", "XJxxxFy",
"http://localhost:1599/home/oauth2callback"); //my return URI
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req0.ContentType = "application/x-www-form-urlencoded";
req0.ContentLength = byteArray.Length;
using (Stream dataStream = req0.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
}
try
{
using (WebResponse response = req0.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
string responseFromServer = reader.ReadToEnd();
var ser = new JavaScriptSerializer();
accessToken = ser.DeserializeObject(responseFromServer);
}
}
}
}
catch (WebException wex){ var x = wex; }
catch (Exception ex){var x = ex;}