2013-02-23 121 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