Google OAuth2错误请求

时间:2015-08-11 06:36:32

标签: c# windows-phone-8.1 youtube-api httpwebrequest google-oauth2

我正在尝试为Windows手机编写一个YouTube应用,我偶然发现了身份验证方面的一些问题。由于某种原因,以下代码无法正常工作,

string url = "https://accounts.google.com/o/oauth2/token?";
string postData = "code=" + str + "&client_id=*********.apps.googleusercontent.com&client_secret=*******&grant_type=authorization_code";


HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);              

byte[] data = Encoding.Unicode.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";                

using (Stream stream =await httpWReq.GetRequestStreamAsync())
    stream.Write(data, 0, data.Length);

HttpWebResponse response =(HttpWebResponse)(await httpWReq.GetResponseAsync());

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

我是HttpWebRequest的新手,所以我可能错过了一些东西,虽然我得到了回复:

  

错误请求

具体而言,虽然我很确定它不是grant_type,但我已经根据文档做了一切。我做错了什么?

1 个答案:

答案 0 :(得分:1)

这可能会解决它

            parameters.Append("code=" + str);
            parameters.Append("&client_id=*****.apps.googleusercontent.com");
            parameters.Append("&client_secret=*****");
            parameters.Append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob:auto");
            parameters.Append("&grant_type=authorization_code");

            string p_params = parameters.ToString();
            byte[] p_data_params = Encoding.UTF8.GetBytes(p_params);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            request.Accept = "application/json";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            Stream dataStream = await request.GetRequestStreamAsync();
            dataStream.Write(p_data_params, 0, p_data_params.Length);
            dataStream.Dispose();

            HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
            Stream responseStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
            string result = readStream.ReadToEnd();

对我来说很好。