トークンを取得しようとするまで、私はこの OAuth2 でうまくやっています。
私はエンコーディングと関係があると思います。
これが私のコードです:
string url = "https://accounts.google.com/o/oauth2/token";
StringBuilder postDataBuider = new StringBuilder();
postDataBuider.AppendLine("code=" + code);
postDataBuider.AppendLine("client_id=" + System.Configuration.ConfigurationManager.AppSettings["GoogleApplicationClientId"].ToString());
postDataBuider.AppendLine("client_secret=" + System.Configuration.ConfigurationManager.AppSettings["GoogleApplicationClientSecret"].ToString());
postDataBuider.AppendLine("redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["AppDomain"] + "Account/YouTubeOAuth2Callback");
postDataBuider.AppendLine("grant_type=authorization_code");
string postDataStr = postDataBuider.ToString();
// byte[] postDataBytes = System.Text.Encoding.GetEncoding("application/x-www-form-urlencoded").GetBytes(postDataStr);
byte[] postDataBytes = System.Text.Encoding.UTF8.GetBytes(postDataStr);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(postDataBytes, 0, postDataBytes.Length);
dataStream.Close();
string responseStr = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
responseStr = readStream.ReadToEnd();
if (String.IsNullOrWhiteSpace(responseStr))
{
throw new Exception("Response is null or empty");
}
}
}
}
エラーについて記録した情報は次のとおりです。
The remote server returned an error: (400) Bad Request.
Response Status: ProtocolError
Response Header: Cache-Control = no-cache, no-store, max-age=0, must-revalidate
Response Header: Pragma = no-cache
Response Header: Expires = Fri, 01 Jan 1990 00:00:00 GMT
Response Header: Date = Tue, 22 May 2012 05:55:54 GMT
Response Header: Content-Type = application/json
Response Header: X-Content-Type-Options = nosniff
Response Header: X-Frame-Options = SAMEORIGIN
Response Header: X-XSS-Protection = 1; mode=block
Response Header: Server = GSE
Response Header: Transfer-Encoding = chunked