gpt4 book ai didi

vb.net - 使用 VB.NET 从 API 读取

转载 作者:行者123 更新时间:2023-12-03 09:03:22 24 4
gpt4 key购买 nike

我希望有人能告诉我如何在 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 是可行的方法吗?如果是这样,您能提供一些示例代码来帮助我吗?

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

最佳答案

这是正确的; HTTP 请求将是最佳选择。您提供的 python 示例代码提到了 header ,也可以使用 WebHeaderCollection 来完成。另一种方法是使用网络客户端。

Web 客户端(无 header )

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()

关于vb.net - 使用 VB.NET 从 API 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48738367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com