首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用VB.NET读取API

使用VB.NET读取API
EN

Stack Overflow用户
提问于 2018-02-12 09:28:05
回答 1查看 3.2K关注 0票数 1

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

我感兴趣的复制代码如下(用Python编写):

代码语言:javascript
复制
import requests

token = "YOUR_APP_TOKEN"

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

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

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

代码语言:javascript
复制
curl "https://api.lifx.com/v1/lights/all" \
     -H "Authorization: Bearer YOUR_APP_TOKEN"

我的问题是:如何在VB.NET中做到这一点?HttpWebRequest会是个不错的选择吗?如果是这样,您能提供一些示例代码来帮助我吗?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-12 10:20:55

这是正确的;HTTP请求是可行的方法。您提供的python示例代码提到了headers,这也可以使用WebHeaderCollection来完成。另一种方法是使用web客户端。

Web客户端(无标头)

代码语言:javascript
复制
Dim client As New WebClient
Dim data As String = client.DownloadString("https://api.lifx.com/v1/lights/all")

具有使用WebRequest的标题

代码语言:javascript
复制
'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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48738367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档