YouTube データにアクセスして変更するために、Google アカウントでユーザーを認証しようとしています。ユーザーのログインと条件の同意から返されたトークンをなんとか取得できましたが、トークンをユーザーの access_token と交換するために POST を実行すると、Json ファイルで「無効な要求」が返されます。
ログインページを表示する方法は次のとおりです。
string url = string.Format("https://accounts.google.com/o/oauth2/auth?client_id=XXXXXXX&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://gdata.youtube.com&response_type=code&access_type=offline");
WBrowser.Navigate(new Uri(url).AbsoluteUri);
を使用しHttpWebRequestて POST を作成しました
string url = "https://accounts.google.com/o/oauth2/token?code=XXXXXX&client_id=XXXXXXXXX&client_secret=XXXXXXXXX&redirect_uri=http://localhost/oauth2callback&grant_type=authorization_code";
HttpWebRequest httpWReq =  (HttpWebRequest)WebRequest.Create(url);
byte[] byteArray = Encoding.UTF8.GetBytes(url);
httpWReq.Method = "POST";
httpWReq.Host = "accounts.google.com";
httpWReq.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
httpWReq.ContentLength = byteArray.Length;
しかし、次の行で失敗します。
HttpWebResponse myHttpWebResponse = (HttpWebResponse)httpWReq.GetResponse();
次のエラーが発生します。
ContentLength>0 または SendChunked==true を設定する場合は、要求本文を指定する必要があります。これを行うには、[Begin]GetResponse の前に [Begin]GetRequestStream を呼び出します。
次に、POST リクエストを次のように TcpClient に変更しました。
TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");
{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(url.ToString());
    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(url.ToString());
    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}
Debug.WriteLine("Response");
StreamReader reader = new StreamReader(sslStream);
while(true) {  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if(line == null)
        break;
    Debug.WriteLine(line);
}
ただし、JSON ファイルで次を返します。
{
  "error" : "invalid_request"
}
私はYoutube APIに従っています: https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Installed_Applications_Flow
ここで OAuth をテストできます: https://developers.google.com/oauthplayground/
これを行う他の方法、または私が持っているものを修正する方法について何か提案はありますか?