I'm making a desktop application in VB.NET that will interact with YouTube. So far I have managed to solve the "problem" of OAuth2 authentication and I have my tokens (auth and refresh). I need to refresh the auth token once every hour but this is not the problem.
I tried to post a comment on a video in many ways, using the http POST and using the YouTube API. On the HTTP request POST I get a "bad request" response and on the YouTube API try I get nothing, no comment posted and no errors. How can I do this? The documentation for the YouTube Data API is corrupted and I can't open it or install it on Visual Studio so I do my tests by trial and error using the little examples that people posted online.
This is the code that I used for the HTTP version:
'create the xml comment as in API example
Dim ContentLenght As Long
Dim xmlData As New System.Xml.XmlDocument()
Dim commentXML As XDocument =
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<content><%= comment %></content>
</entry>
ContentLenght = commentXML.ToString.Length
'---------------------------------------------------------
'create the POST request to submit the comment
Dim sentXml As Byte() = System.Text.Encoding.ASCII.GetBytes(commentXML.ToString)
Dim url = "http://gdata.youtube.com/feeds/api/videos/" & videoID & "/comments"
Dim req As New WebClient
req.Headers.Add("Host: gdata.youtube.com")
req.Headers.Add("Length:" & ContentLenght)
req.Headers.Add("Content-Type: application/atom+Xml")
req.Headers.Add("Authorization: Bearer " & Token)
req.Headers.Add("GData-Version: 2")
req.Headers.Add("X-GData-Key: key=" & developerKey)
Dim response As Byte() = req.UploadData(url, "POST", sentXml)
The API code that I tried is:
Dim commentingSettings As New YouTubeRequestSettings(appName, developerKey, Token)
Dim lcommentingRequest As New YouTubeRequest(commentingSettings)
Dim video As New Video()
video.VideoId = "JEvV0RHMU-Y"
Dim comm As New Comment
comm.Content = "comm text here"
lcommentingRequest.AddComment(video, comm)
I have solved the problem using the Youtube API. The problem was the way the "video" object is created. Here is the working code for people that need it:
Dim commentingSettings As New YouTubeRequestSettings(appName, developerKey, Token)
Dim lcommentingRequest As New YouTubeRequest(commentingSettings)
Dim videodUrl As New Uri(String.Format("{0}/{1}",Google.GData.YouTube.YouTubeQuery.DefaultVideoUri, "BtrFZmZjalE"))
Dim video As Google.YouTube.Video = request.Retrieve(Of Google.YouTube.Video)(videoEdUrl)
Dim comm As New Comment
comm.Content = "comm text here"
lcommentingRequest.AddComment(video, comm)
Now the code will work!
The new question is: How do I get the comment ID after I posted? Is there a way to get it from the code above (some server response or something)? ... but as Chris M. suggested I will create another question for this...