我正在尝试建立一个VB.net网站,以在频道名称旁边显示图像(如果正在直播)。我目前已建立包含URL和图像的页面,并且已经设置了搜索API:
我知道这是可行的,因为在正常跟随链接时,我会看到JSON。
唯一的问题是我不知道如何在VB中发送HTTP请求。我本来只是在测试时在page_load上执行此请求,但据我所知:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim request As WebRequest = WebRequest.Create("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[ChannelID]&type=video&eventType=live&key=[API-KEY]")
End Sub
如何在VB.net中发送此请求?我将如何读取返回的JSON?
答案 0 :(得分:0)
我能够将JSON
返回到String
变量中:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim request As WebRequest = WebRequest.Create("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=[ChannelID]&type=video&eventType=live&key=[API-KEY]")
Dim streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream)
Dim youtube As String = streamReader.ReadToEnd
MsgBox(youtube)
End Sub
我已将此功能修改为允许检查任何通道ID的功能。它最初返回了boolean
,但我对其进行了调整,使其返回了integer
来执行错误处理,而无需修改return语句或后面代码的其他部分中的函数调用。
Protected Function IsLiveStreaming(channelID As String) As Integer
Try
Dim request As WebRequest = WebRequest.Create("https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" & channelID & "&type=video&eventType=live&key=[API-KEY]")
Dim response As WebResponse = request.GetResponse
Dim streamReader As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream)
Dim youtube As String = streamReader.ReadToEnd
Dim obj As Newtonsoft.Json.Linq.JObject = JObject.Parse(youtube)
Dim arr As JArray = obj("items")
If arr.Count > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
'Typically a 403 error from exceeding quota on YouTube api
Return -1
End Try
Return False
End Function