繁体   English   中英

无法通过方法帖子的WebRequest获得响应

[英]Unable to get response with WebRequest of method post

我想使用谷歌的OAUTH2.0验证访问我网站的用户。

我已成功获得authorization_code作为响应,现在当我获取访问令牌时向Google发出“POST请求”时,我遇到了问题。 问题是请求一直在持续,我没有得到任何回应。

我在下面写的代码有什么问题吗?

StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string addons = "/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=123029216828.apps.googleusercontent.com&client_secret={zd5dYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code";

request.ContentLength = addons.Length;

Stream str = request.GetResponse().GetResponseStream();
StreamReader r = new StreamReader(str);
string a = r.ReadToEnd();

str.Close();
r.Close();

正如我在评论中提到的,您的代码中只有一些小错误。 就目前而言,你实际上并没有发布任何东西。 我假设您打算发送postData字符串。

以下应该有效:

//Build up your post string
StringBuilder postData = new StringBuilder();
postData.Append("code=" + Request.QueryString["code"]);
postData.Append("&client_id=123029216828.apps.googleusercontent.com");
postData.Append("&client_secret=zd5dYB9MXO4C5vgBOYRC89K4");
postData.Append("&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");

//Create a POST WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token?code=" + Request.QueryString["code"] + "&client_id=124545459218.apps.googleusercontent.com&client_secret={zfsgdYB9MXO4C5vgBOYRC89K4}&redirect_uri=http://localhost:4180/GAuth.aspx&grant_type=authorization_code");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

//Write your post string to the body of the POST WebRequest
var sw = new StreamWriter(request.GetRequestStream());
sw.Write(postData.ToString());
sw.Close();

//Get the response and read it
var response = request.GetResponse();
var raw_result_as_string = (new StreamReader(response.GetResponseStream())).ReadToEnd();

您刚刚错过了将字符串附加到POST WebRequest的部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM