使用 VB.NET 从 API 读取 [英] Reading from API using VB.NET

查看:24
本文介绍了使用 VB.NET 从 API 读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能告诉我如何在 VB.NET 中构建 HttpWebRequest 以便能够使用以下 API 检索信息:https://api.developer.lifx.com/docs/list-lights

I was hoping someone could tell me how to structure a HttpWebRequest in VB.NET to be able to retrieve information using the following API: https://api.developer.lifx.com/docs/list-lights

我有兴趣复制的代码在这里(在 Python 中):

The code I am interested in replicating is here (in 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 版本:

A cURL version of this can be seen here:

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

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

My question is: how do I do this in VB.NET? Would a HttpWebRequest be the way to go? If so, could you please assist me by providing some example code?

我希望检索我所有灯的列表.

I am hoping to retrieve a list of all my lights.

推荐答案

正确;HTTP请求将是要走的路.您提供的 python 示例代码提到了也可以使用 WebHeaderCollection 完成的标头.另一种方法是使用网络客户端.

That is correct; A HTTP Request would be the way to go. The python sample code you provided mentions headers which can also be done using a WebHeaderCollection. One other way to do it is using a web client.

Web 客户端(无标题)

Web client (No headers)

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

使用 WebRequest 的标题

With Headers using 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()

这篇关于使用 VB.NET 从 API 读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆