使用R中的参数构建请求URL的最佳方法是什么?到目前为止,我想出了这个:
library(magrittr)
library(httr)
library(data.table)
url <- list(hostname = "geo.stat.fi/geoserver/vaestoalue/wfs",
scheme = "https",
query = list(service = "WFS",
version = "2.0.0",
request = "GetFeature",
typename = "vaestoalue:kunta_vaki2017",
outputFormat = "application/json")) %>%
setattr("class","url")
request <- build_url(url)
Run Code Online (Sandbox Code Playgroud)
我喜欢我现在的代码是,我可以轻松更改参数值并重建URL.
此外,生成的url正确地进行了html编码:
https://geo.stat.fi/geoserver/vaestoalue/wfs/?service=WFS&version=2.0.0&request=GetFeature&typename=vaestoalue%3Akunta_vaki2017&outputFormat=application%2Fjson
Run Code Online (Sandbox Code Playgroud)
但是加载data.table库,只是为了构建一个url,感觉不对.这样做有好处吗?
您绝对不需要data.table构建 URL。正如 Jos\xc3\xa9 所指出的,它被加载为使用一个方便的函数,你可以用它来模仿:
set_class <- function(o, v) { class(o) <- v ; invisible(o) }\nRun Code Online (Sandbox Code Playgroud)\n\n另外,除非目标是拥有 URL 而只是从站点读取数据,否则您也可以只使用httr动词:
httr::GET(\n url = "https://geo.stat.fi/geoserver/vaestoalue/wfs",\n query = list(\n service = "WFS",\n version = "2.0.0",\n request = "GetFeature",\n typename = "vaestoalue:kunta_vaki2017",\n outputFormat = "application/json"\n )\n) -> res\n\n\ndat <- httr::content(res)\n\nstr(dat, 1)\n## List of 5\n## $ type : chr "FeatureCollection"\n## $ totalFeatures: int 311\n## $ features :List of 311\n## $ crs :List of 2\n## $ bbox :List of 4\nRun Code Online (Sandbox Code Playgroud)\n