使用R 访问Dropbox的示例(不使用rdrop2)
rdrop2目前不再维护。为了防万一出错,我想直接使用DropBox API。这采用了OAuth 2.0授权流程,初次阅读时并不直观。DropBox的文档也没能让我更进一步。我想要的是一个可用的R 示例。
我的问题是:
如何在不使用rdrop2包的情况下,使用R 列出一个DropBox目录?
我已经尝试了多种方法,使用授权码、刷新令牌、访问令牌,以及以各种格式的POST请求头和请求体,混合出各种随机组合。
以下内容几乎起作用,直到第二天令牌过期。
DropBoxList <- httr::POST(
url = "https://api.dropboxapi.com/2/files/list_folder",
add_headers(Authorization = paste("Bearer","AccessToken")),
content_type_json(),
body = toJSON(list(path = "/Directory/SubDirectory"),auto_unbox = TRUE))
DropBoxListData <- fromJSON(httr::content(DropBoxList,
type ="text",encoding="UTF- 8"),flatten = TRUE)
DropBoxFiles <- DropBoxListData$entries
最终……终于起作用了。请看答案。
解决方案
前面这三步只需要做一次。
步骤1。创建一个DropBox应用。这需要前往 https://www.dropbox.com/developers,选择“App Console”标签,然后点击“Create App”按钮,并按照各项菜单操作。在为应用创建的DropBox页面上,会有一个“App key”和一个“App secret”。把它们写在纸上以备后用。
步骤2。通过访问此网站获取一个临时的(10分钟)授权码(把
网站会请求你授权访问你的DropBox应用,最终会给你一串较长的字符。这就是你的授权码。把它写在纸上。
步骤3。使用下面的R 代码获取一个永久刷新码。把它写在纸上。
#Get app_key and app_secret from DropBox.com/developers
app_key <- "stringOfCharacters"
app_secret <- "differentStringOfCharacters"
#Get the authorisation code from https://www.dropbox.com/oauth2/authorize?client_id=<APP_KEY>&token_access_type=offline&response_type=code
authorization_code <- "anotherStringOfCharacters"
# Request a permanent refresh token
RefreshTokenResponse <- httr::POST(
url = "https://api.dropbox.com/oauth2/token",
body = list(
code = authorization_code,
grant_type = "authorization_code",
client_secret = app_secret,
client_id = app_key
),
encode="form"
)
Refresh_token <- httr::content(RefreshTokenResponse)$refresh_token
步骤4。获取一个临时(3小时)访问码。每次想使用DropBox API之前都需要执行此步骤。
AccessTokenResponse <- httr::POST(
url = "https://api.dropbox.com/oauth2/token",
body = list(
refresh_token = Refresh_token,
grant_type = "refresh_token",
client_secret = app_secret,
client_id = app_key
),
encode="form"
)
Access_token <- httr::content(AccessTokenResponse)$access_token
步骤5。在对DropBox API的调用中使用访问令牌。例如,用于列出目录内容:
DropBoxPathToList <- "/Directory/SubDirectory"
DropBoxList <- httr::POST(
url = "https://api.dropboxapi.com/2/files/list_folder",
add_headers(Authorization = paste("Bearer",Access_token)),
content_type_json(),
body = toJSON(list(path = DropBoxPathToList),auto_unbox = TRUE))
DropBoxListData <- fromJSON(httr::content(DropBoxList, type ="text",encoding="UTF-8"),flatten = TRUE)
DropBoxFiles <- DropBoxListData$entries