Visual Studio 使用VB.NET阅读API

2ic8powd  于 2023-06-24  发布在  .NET
关注(0)|答案(2)|浏览(122)

我希望有人能告诉我如何在VB.NET中构造一个HttpWebRequest,以便能够使用以下API检索信息:https://api.developer.lifx.com/docs/list-lights
我感兴趣的代码复制在这里(在Python中):

import requests

token = "YOUR_APP_TOKEN"

headers = {
    "Authorization": "Bearer %s" % token,
}

response = requests.get('https://api.lifx.com/v1/lights/all', headers=headers)

这个的cURL版本可以在这里看到:

curl "https://api.lifx.com/v1/lights/all" \
     -H "Authorization: Bearer YOUR_APP_TOKEN"

我的问题是:我如何在VB.NET中做到这一点?HttpWebRequest会是一条出路吗?如果是的话,你能帮助我提供一些示例代码吗?
我希望检索我所有的灯的列表。

gopyfrb3

gopyfrb31#

这是正确的; HTTP请求将是一种方法。您提供的Python示例代码提到了头文件,也可以使用WebHeaderCollection来完成。另一种方法是使用Web客户端。
Web客户端(无标头)

Dim client As New WebClient
Dim data As String = client.DownloadString("https://api.lifx.com/v1/lights/all")

使用WebRequest的Header

'String for token
Dim tokenString As String = "YOUR_APP_TOKEN"
'Stream for the responce
Dim responseStream As System.IO.Stream
'Stream reader to read the stream to a string
Dim stringStreamReader As System.IO.StreamReader
'String to be read to
Dim responseString As String
'The webrequest that is querying
Dim webRequest As WebRequest = WebRequest.Create("https://api.lifx.com/v1/lights/all")
'The collection of headers
Dim webHeaderCollection As WebHeaderCollection = webRequest.Headers
'Adding a header
webHeaderCollection.Add("Authorization:Bearer " + tokenString)
'The web responce
Dim webResponce As HttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
'Reading the web responce to a stream
responseStream = webResponce.GetResponseStream()
'Initializing the stream reader with our stream
stringStreamReader = New StreamReader(responseStream)
'Reading the stream to our string
responseString = stringStreamReader.ReadToEnd.ToString
'Ending the web responce
webResponce.Close()
j7dteeu8

j7dteeu82#

Imports System.Net
    Imports Newtonsoft.Json.Linq

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim json As String = New System.Net.WebClient().DownloadString("API URL")
    Dim parsejson As JObject = JObject.Parse(json)
    Label1.Text = parsejson.ToString()
End Sub

相关问题