我希望有人能告诉我如何在VB.NET中构造HttpWebRequest,以便能够使用以下接口检索信息: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会是个不错的选择吗?如果是这样,您能提供一些示例代码来帮助我吗?
我希望能检索到我所有灯光的列表。
发布于 2018-02-12 10:20:55
这是正确的;HTTP请求是可行的方法。您提供的python示例代码提到了headers,这也可以使用WebHeaderCollection来完成。另一种方法是使用web客户端。
Web客户端(无标头)
Dim client As New WebClient
Dim data As String = client.DownloadString("https://api.lifx.com/v1/lights/all")具有使用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()https://stackoverflow.com/questions/48738367
复制相似问题