我正在尝试通过Google的oAuth(v2)获取访问令牌。我正在使用ASP.NET 4.0 Web窗体(C#)。我遇到的问题是当我提交HttpWebRequest时,我收到错误请求错误。我正在使用我在这里找到的代码(http://blog.movereem.nl/using-google-apis-through-oauth-20/)。这是我在pageLoad事件中的代码:
string strCode = "";
string strClientID = "********.apps.googleusercontent.com";
string strClientSecret = "**********";
string strRedirectURI = "http://www.example.com";
if (Request.QueryString["code"] != null && Request.QueryString["code"].ToString() != "")
{
strCode = Request.QueryString["code"].ToString();
StreamWriter sw = new StreamWriter(Server.MapPath("~\\") + "code.txt");
sw.WriteLine(Request.QueryString["code"].ToString());
sw.Close();
string queryStringFormat = "code={0}&redirect_uri={1}&client_id={2}&client_secret={3}&grant_type=authorization_code";
string postcontents = string.Format(queryStringFormat
, HttpUtility.UrlEncode(strCode)
, HttpUtility.UrlEncode(strClientID)
, HttpUtility.UrlEncode(strClientSecret)
, HttpUtility.UrlEncode(strRedirectURI));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://accounts.google.com/o/oauth2/token");
request.Method = "POST";
byte[] postcontentsArray = Encoding.UTF8.GetBytes(postcontents);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postcontentsArray.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postcontentsArray, 0, postcontentsArray.Length);
requestStream.Close();
WebResponse response = request.GetResponse();//Error Happens Here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
reader.Close();
responseStream.Close();
response.Close();
//return SerializeToken(responseFromServer);
}
}
}
感谢任何帮助。感谢。
答案 0 :(得分:0)
乍一看,代码看起来大致正确,但我认为您的string.Format
参数的顺序与queryStringFormat
的顺序不同:
string queryStringFormat = "code={0}&redirect_uri={1}&client_id={2}&client_secret={3}&grant_type=authorization_code";
string postcontents = string.Format(queryStringFormat
, HttpUtility.UrlEncode(strCode)
// Redirect URI should be here (or switch the order above)
, HttpUtility.UrlEncode(strClientID)
, HttpUtility.UrlEncode(strClientSecret)
, HttpUtility.UrlEncode(strRedirectURI));