我正在创建一个 VB.NET 程序,我想与 dropbox 交互。我从“list_folder”命令开始,它将返回指定路径上的内容。这是您可以使用该命令的 URL:
https://dropbox.github.io/dropbox-api-v2-explorer/#files_list_folder
提供的HTTP请求语法如下:
POST /2/files/list_folder
Host: https://api.dropboxapi.com
User-Agent: api-explorer-client
Authorization: Bearer HBNBvdIls8AA12AAFTvyzhNJrdwwpQcswxpRVjmwRIJANPIea7Jc1Ke
Content-Type: application/json
{
"path": "/Backups"
}
我想做的相当于 VB.NET 命令。这是我到目前为止所拥有的:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uri As String = "https://api.dropboxapi.com/2/files/list_folder"
Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(uri)
request.Method = "POST"
request.UserAgent = "api-explorer-client"
' this is wrong, need to supply an 'authorization token' somehow:
Dim credentials As New Net.NetworkCredential("username", "password")
request.Credentials = credentials
request.ContentType = "application/json"
'request.ContentLength = ???
' how do I set content to the "path: backups" data?
Dim response As Net.HttpWebResponse = request.GetResponse
Debug.Print(response.StatusDescription)
Dim dataStream As IO.Stream = response.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
Dim responseFromServer As String = reader.ReadToEnd() ' Read the content.
MsgBox(responseFromServer) ' Display the content.
' Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()
End Sub
我缺少的是以某种方式将文档指定的“path”:“/Backups”数据编码到请求对象中。我还缺少如何将“授权”访问令牌编码到请求中。 (上面我使用了用户名/密码,但这可能是错误的。)
有人可以帮我完成 VB.NET HTTP 请求吗?非常感谢。
** 根据 the_lotus 的有用链接更新新代码——这有效,谢谢!:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim uri As String = "https://api.dropboxapi.com/2/files/list_folder"
Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(uri)
request.Method = "POST"
request.UserAgent = "api-explorer-client"
request.Headers.Add("Authorization", "Bearer HBN-BvdIlsAAAFTyAQzhNJrBNINPIea7Jc1Ke")
'{
'"path": "/Backups"
'}
Dim json_data As String = "{"+ Chr(34) + "path" + Chr(34) + ": " + Chr(34) + "/Backups" + Chr(34) + "}"
request.ContentType = "application/json"
Dim json_bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(json_data)
request.ContentLength = json_bytes.Length
Dim stream As IO.Stream = request.GetRequestStream
stream.Write(json_bytes, 0, json_bytes.Length)
Dim response As Net.HttpWebResponse = request.GetResponse
Debug.Print(response.StatusDescription)
Dim dataStream As IO.Stream = response.GetResponseStream()
Dim reader As New IO.StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
Dim responseFromServer As String = reader.ReadToEnd() ' Read the content.
MsgBox(responseFromServer) ' Display the content.
' Cleanup the streams and the response.
reader.Close()
dataStream.Close()
response.Close()
End Sub