如何使用基本身份验证发出并发 HTTP 请求

How to make concurrent HTTP requests with basic authentication

我的目标是从 Shopify 导入客户的订单历史记录。 Shopify 只允许我在每个请求中导入 250 个订单,但我的客户有数千个。

这是(基本上)我目前使用 httr 的工作解决方案,它非常慢

fetchedList <- list()

# Loop through pages of orders and collect them
for(pg in 1:10){

  requestURL <- paste0("https://abc-store.myshopify.com/admin/orders.json?page=", p)

  fetched <- httr::GET(
    url = requestURL,
    httr::add_headers(Accept = "application/json"),
    httr::authenticate(user = "foo", password = "bar")
  )

  # Append the fetched response to fetchedList 
  fetchedList <- c(fetchedList, list(fetched))
}

# Process the results...

我想通过发出多个并发请求来加快速度。我怎样才能做到这一点?似乎 curl and RCurl 都支持这个,但我对 HTTP 还很陌生,无法使任何一个解决方案工作。

您应该使用 multi api 进行并发请求。请参阅 ?multi_run 的手册页或小插图中有关 async requests 的部分。

也有包装 multi api 的包,试图让它更容易。 crul package (note crul is not a typo :) or more if you want to get real fancy the async 包。

感谢@Jeroen 向我指出 crul 包。当时,crul 实际上并没有设置这个功能,但我和维护者谈过,他实现了它。所以,从 v 0.5.2.9100 开始,我可以做到

dd <- Async$new(urls = c(
  'https://abc-store.myshopify.com/admin/orders.json?page=1',
  'https://abc-store.myshopify.com/admin/orders.json?page=2',
  'https://abc-store.myshopify.com/admin/orders.json?page=3'
))
res <- dd$get(auth = auth(user = "foo", pwd = "bar"))
vapply(res, function(z) z$status_code, double(1))
vapply(res, function(z) z$success(), logical(1))
lapply(res, function(z) z$parse("UTF-8"))