调用Dropbox API获取文件列表时遇404错误求助
问题
首次接触Dropbox API,编写代码尝试获取文件列表时遇到错误:Access dropbox file - The remote server returned an error: (404) Not Found。修改安全协议类型后仍出现相同错误,代码如下:
Dim token As String token = "sl.B6........." Dim _command As String _command = "https://api.dropboxapi.com/2/files/list_folder" Dim Request As HttpWebRequest Request = HttpWebRequest.Create(_command) Request.Method = "GET" Request.KeepAlive = True Request.ContentType = "application/x-www-form-urlencoded" Request.UserAgent = "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36" Request.AllowAutoRedirect = True Request.Headers.Add("Authorization", "Bearer " & token) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Dim Response As HttpWebResponse = Request.GetResponse()
解决方法
- 核心错误:请求方法不匹配
Dropbox的/2/files/list_folder接口仅支持POST请求,你代码中使用的GET方法会直接触发404错误,这和安全协议无关。 - 具体修正点:
- 将请求方法改为
POST:Request.Method = "POST" - 接口要求JSON格式的请求体(即使查询根目录,也需要传入
{"path": ""}),需添加请求内容 - 把
ContentType改为application/json,匹配接口的请求格式要求
- 将请求方法改为
修正后的完整代码示例:
Dim token As String token = "sl.B6........." Dim _command As String _command = "https://api.dropboxapi.com/2/files/list_folder" Dim Request As HttpWebRequest = CType(HttpWebRequest.Create(_command), HttpWebRequest) Request.Method = "POST" Request.KeepAlive = True Request.ContentType = "application/json" Request.UserAgent = "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36" Request.AllowAutoRedirect = True Request.Headers.Add("Authorization", "Bearer " & token) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 ' 添加JSON请求体 Dim postData As String = "{""path"": """"}" Dim byteArray As Byte() = System.Text.Encoding.UTF8.GetBytes(postData) Request.ContentLength = byteArray.Length Using dataStream As Stream = Request.GetRequestStream() dataStream.Write(byteArray, 0, byteArray.Length) End Using ' 读取响应内容 Using Response As HttpWebResponse = CType(Request.GetResponse(), HttpWebResponse) Using reader As New StreamReader(Response.GetResponseStream()) Dim responseText As String = reader.ReadToEnd() ' 此处可处理响应内容,比如输出或解析 Console.WriteLine(responseText) End Using End Using
内容的提问来源于stack exchange,提问作者Luca Geremei
相关产品推荐
相关产品推荐

