在R中调用Global Fishing Watch API时遇curl意外符号错误
问题原因
你直接把终端/命令行环境下的curl命令写到R脚本里了,R作为编程语言无法识别这种shell语法,因此触发“unexpected symbol”错误。
修正后的代码
方法1:用httr包(更贴合R的代码风格)
install.packages(c("curl", "httr")) library(httr) # 获取授权令牌 key <- gfw_auth() # 构造请求参数和头部 request_url <- "https://gateway.api.globalfishingwatch.org/v2/events" request_params <- list( vessels = "9b3e9019d-d67f-005a-9593-b66b997559e5", datasets = "public-global-fishing-events:latest", `start-date` = "2017-01-01", `end-date` = "2017-01-31", limit = 1, offset = 0 ) auth_header <- add_headers(Authorization = paste0("Bearer ", key)) # 发送请求并解析结果 response <- GET(request_url, query = request_params, auth_header) result_data <- content(response, as = "parsed")
方法2:用curl包
install.packages("curl") library(curl) library(jsonlite) key <- gfw_auth() # 构造请求URL和头部 request_url <- "https://gateway.api.globalfishingwatch.org/v2/events?vessels=9b3e9019d-d67f-005a-9593-b66b997559e5&datasets=public-global-fishing-events:latest&start-date=2017-01-01&end-date=2017-01-31&limit=1&offset=0" request_handle <- new_handle() handle_setheaders(request_handle, "Authorization" = paste0("Bearer ", key) ) # 发送请求并解析JSON结果 response <- curl_fetch_memory(request_url, handle = request_handle) result_data <- fromJSON(rawToChar(response$content))
核心注意事项
- R脚本中必须用对应R包的函数实现HTTP请求,不能直接复制终端的curl命令
- 授权头里的令牌需要用
paste0把Bearer和变量key拼接起来,否则R会把key当成普通字符串,无法正确传递令牌
内容的提问来源于stack exchange,提问作者Michael Brady
相关产品推荐
相关产品推荐

