2
當我運行此代碼調用Google API時,我得到的只是一個'錯誤請求'錯誤,但我不知道錯誤發生在哪裏。c#WebRequest到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());
}
你是否看過電線上的請求,例如與Wireshark? –
嗨,約翰,我在小提琴手看過它,但它已經過了https,所以我不確定我能從中收集到什麼? –
老鼠,我沒有發現HTTPS-ness。你至少檢查過'postData'看起來是否合理? –