2013-02-23 117 views
0

我想验证谁使用谷歌的OAUTH2.0访问我的网站的用户。无法得到响应WebRequest的方法

我已经成功地获得了授权代码的响应,现在当我在获取访问令牌时向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(); 
+0

你正在构建你的'postData'字符串,而不是做任何事情。你能解释一下'addons'和'postData'的用途吗?你想要发布一个或两个这些字符串?用于内容长度计算的 – JoshVarty 2013-02-23 06:53:55

+0

插件。正如你所说我不使用发布数据,因为我提到了webrequest.create本身的所有内容 – 2013-02-23 07:14:35

+0

其工作...感谢'JoshVarty'你的答案。 – 2013-02-23 07:27:59

回答

2

正如我在我的评论中提到的,你的代码中只有一些小错误。就目前而言,你实际上并没有发布任何东西。我假设你打算发送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(); 

你只是缺少在您连接字符串到您的文章的WebRequest的部分。

+0

其工作..感谢您的帮助 – 2013-02-23 07:29:50