Vb.net 如何使用Google YouTube API检索和显示第一个结果链接?
我试图使用YouTube API V3来提取在YouTube上搜索内容时出现的第一个视频的URL 因此,我需要“按关键字搜索”,并将Vb.net 如何使用Google YouTube API检索和显示第一个结果链接?,vb.net,winforms,google-api,youtube-api,Vb.net,Winforms,Google Api,Youtube Api,我试图使用YouTube API V3来提取在YouTube上搜索内容时出现的第一个视频的URL 因此,我需要“按关键字搜索”,并将maxResults参数的值更改为1 由于代码是C#,我尝试使用在线转换器,但遇到了一个问题。我创建了一个新类,插入所有这些代码,并通过NuGet安装了Google API和YouTube API 编辑:此代码已从控制台应用程序转换为WinForm: Imports System Imports System.Collections.Generic Imports
maxResults
参数的值更改为1
由于代码是C#,我尝试使用在线转换器,但遇到了一个问题。我创建了一个新类,插入所有这些代码,并通过NuGet安装了Google API和YouTube API 编辑:此代码已从控制台应用程序转换为WinForm:
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Upload
Imports Google.Apis.Util.Store
Imports Google.Apis.YouTube.v3
Imports Google.Apis.YouTube.v3.Data
Namespace YouTube
''' <summary>
''' YouTube Data API v3 sample: search by keyword.
''' Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
''' See https://developers.google.com/api-client-library/dotnet/get_started
'''
''' Set ApiKey to the API key value from the APIs & auth > Registered apps tab of
''' https://cloud.google.com/console
''' Please ensure that you have enabled the YouTube Data API for your project.
''' </summary>
Public Async Function Run(ByVal videos As String) As Task(Of String)
Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
.ApiKey = "REPLACE_ME",
.ApplicationName = [GetType]().ToString()
})
Dim searchListRequest = youtubeService.Search.List("snippet")
searchListRequest.Q = "Google" ' Replace with your search term.
searchListRequest.MaxResults = 1
' Call the search.list method to retrieve results matching the specified query term.
Dim searchListResponse = Await searchListRequest.ExecuteAsync()
Return searchListResponse.Items.FirstOrDefault()?.Id.VideoId
End Function
End Class
End Namespace
但是消息框显示为空。有没有一种方法可以将它称为已更改的
searchListRequest.Q
?例如:
msgbox(wait Run(关键字))
由于要调用搜索类Run()
方法(此处重命名为GetResultsAsync()
以匹配标准命名约定),您可以:
- 创建新类文件,将其添加到项目(或类库)
- 将异步方法设置为static(
),这样您就可以直接调用它(这不是必需的,但这样处理搜索结果似乎更好。当然,您可以创建Shared
类的实例)GoogleSearch
- 使用文本框的内容将搜索项传递给方法。
- 您可以在
事件中处理Enter键TextBox.KeyDown
- 如果需要,还可以添加执行相同操作的按钮
- 您可以在
- 在YouTube.GoogleSearch.GetResultAsync()中
- 设置
<代码>[GetType]()。ToString()是C#的错误翻译,即使更正了,在这里也没什么用处。或者直接使用为注册创建的名称.ApplicationName=Application.ProductName
- 将
searchListRequest.ExecuteAsync()的第一个结果返回为
:如果没有返回结果,该方法将返回空字符串(searchListResponse.Items.FirstOrDefault()?.Id.VideoId
)Nothing
- 设置
- 添加并重载
,该函数接受用于在一段时间后取消任务的超时参数和允许取消HTTP请求任务的方法GetResultAsync()
GoogleSearch
类重命名为您喜欢的名称:)
使用按钮或TextBox.KeyDown事件调用
GetResultAsync()
方法,并在另一个文本框中显示结果:
Private Async Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
If (e.KeyCode = Keys.Enter) Then
e.SuppressKeyPress = True
txtSearch.Enabled = False
SomeTextBox.Text = Await YouTube.GoogleSearch.GetResultAsync(txtSearch.Text)
txtSearch.Enabled = True
End If
End Sub
Private Async Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.Enabled = False
SomeTextBox.Text = Await YouTube.GoogleSearch.GetResultAsync(txtSearch.Text)
btnSearch.Enabled = True
End Sub
Private Sub btnCancelSearch_Click(sender As Object, e As EventArgs) Handles btnCancelSearch.Click
YouTube.GoogleSearch.Cancel()
End Sub
' Call Cancel() when the Form closed
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
YouTube.GoogleSearch.Cancel()
End Sub
修改后的类对象
► 注意:应将A传递给ExecuteAsync()
方法:如果用户同时关闭表单,则需要取消此任务,以处理FormClosing
或FormClosed
事件。与此处显示的内容类似:
GoogleSearch
类可以是internal
(Friend
)
编辑:
- 添加了一个重载,允许在取消请求之前指定超时(毫秒)
- 添加了一个静态的
取消()
Private Async Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
If (e.KeyCode = Keys.Enter) Then
e.SuppressKeyPress = True
txtSearch.Enabled = False
SomeTextBox.Text = Await YouTube.GoogleSearch.GetResultAsync(txtSearch.Text)
txtSearch.Enabled = True
End If
End Sub
Private Async Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.Enabled = False
SomeTextBox.Text = Await YouTube.GoogleSearch.GetResultAsync(txtSearch.Text)
btnSearch.Enabled = True
End Sub
Private Sub btnCancelSearch_Click(sender As Object, e As EventArgs) Handles btnCancelSearch.Click
YouTube.GoogleSearch.Cancel()
End Sub
' Call Cancel() when the Form closed
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
YouTube.GoogleSearch.Cancel()
End Sub
Imports System.Threading.Tasks
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.YouTube.v3
Imports Google.Apis.YouTube.v3.Data
Namespace YouTube
Public Class GoogleSearch
Private Shared cts As CancellationTokenSource = Nothing
Public Shared Async Function GetResultAsync(ByVal searchCriteria As String) As Task(Of String)
Return Await GetResultAsync(searchCriteria, -1)
End Function
Public Shared Async Function GetResultAsync(ByVal searchCriteria As String, timeoutMilliseconds As Integer) As Task(Of String)
If cts Is Nothing Then cts = New CancellationTokenSource(timeoutMilliseconds)
Dim youtubeService = New YouTubeService(New BaseClientService.Initializer() With {
.ApiKey = "REPLACE_ME",
.ApplicationName = Application.ProductName
})
Dim searchListRequest = youtubeService.Search.List("snippet")
searchListRequest.Q = searchCriteria
searchListRequest.MaxResults = 1
Try
Dim searchListResponse = Await searchListRequest.ExecuteAsync(cts.Token)
Return searchListResponse.Items.FirstOrDefault()?.Id.VideoId
Catch exTCE As TaskCanceledException
' Do whatever you see fit here
'MessageBox.Show(exTCE.Message)
Return Nothing
Finally
Cancel(False)
End Try
End Function
Public Shared Sub Cancel()
Cancel(True)
End Sub
Private Shared Sub Cancel(cancelCTS As Boolean)
If cancelCTS Then cts?.Cancel()
cts?.Dispose()
cts = Nothing
End Sub
End Class
End Namespace