如何使用R编程语言缩短URL

264 阅读1分钟

在本教程中,我们将看到如何使用R编程语言缩短URL。教程中使用的API是免费的,使用前不需要任何注册或登录。当你需要与团队分享一些链接时,这尤其有用。长的URL看起来没有吸引力,而且在复制粘贴时容易出错。

在下面的代码中,我们正在使用is.gdv.gdAPI服务。它们之间唯一的区别是,v.gd显示链接预览,并不自动重定向到原始长URL。而is.gd

会自动带你到原始网址,不显示任何预览。在下面的用户定义的R函数中,默认linkPreview被设置为FALSE。

library(httr)
library(jsonlite)

ShortURL <- function(link, linkPreview = FALSE) {
  
  api <- if(linkPreview) {"http://v.gd/create.php?format=json"} else {"http://is.gd/create.php?format=json"}
  query <- list(url = link)
  request <- httr::GET(api, query = query)
  content <- httr::content(request, as = "text", encoding = "utf-8")
  result <- jsonlite::fromJSON(content)
  
  return(result)
  
}

ShortURL("https://www.listendata.com/2021/01/run-sas-in-python-without-installation.html")

测试缩短的URL是否有效

Shorter <- ShortURL("https://www.listendata.com/2021/01/run-sas-in-python-without-installation.html")
browseURL(Shorter$shorturl)