[英]c# WebRequest to Google API Bad Request
当我运行此代码来调用Google API时,得到的只是一个“错误请求”错误,但我不知道我要去哪里。
从Google的授权页面上可以正常返回代码,这是代码到达下面的部分失败的原因。 请有人告诉我我要去哪里错了吗?
我知道有用于此的库,但是我正在尝试了解如何以RESTful方式进行此学习。
谢谢
var code = Request.QueryString["code"];
var accessToken = string.Empty;
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
"xxxx.apps.googleusercontent.com",
"xxx",
Url.Encode("http://localhost/home/callback")
); //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).ToString();
}
}
}
}
catch (WebException wex)
{
Debug.WriteLine(wex.ToString());
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
对于您为客户端ID返回URI在API控制台中输入的内容以及在代码中输入的内容,Google API非常挑剔。
我错过了后面的斜线。 就这些。 学习到教训了...
感谢乔恩(Jon)和桑迪普(Sandeep)的帮助,通过比较网络流量和应该发送的内容为我指明了正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.