使用 VB.NET 从 API 读取

tac*_*per 2 vb.net visual-studio

我希望有人能告诉我如何在 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)
Run Code Online (Sandbox Code Playgroud)

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

curl "https://api.lifx.com/v1/lights/all" \
     -H "Authorization: Bearer YOUR_APP_TOKEN"
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何在 VB.NET 中执行此操作?HttpWebRequest 是可行的方法吗?如果是这样,您能提供一些示例代码来帮助我吗?

我希望检索我所有灯光的列表。

tob*_*sen 5

那是对的; HTTP 请求将是最佳选择。您提供的 python 示例代码提到了标头,也可以使用WebHeaderCollection. 另一种方法是使用网络客户端。

Web 客户端(无标头)

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

使用 WebRequest 的标头

'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()
Run Code Online (Sandbox Code Playgroud)