使用rgbif包occ_search/occ_download时遇HTTP/2流异常求助
使用rgbif包时的HTTP/2流错误问题
出现以下无固定复现规律的错误,难以定位根因:
Error in curl::curl_fetch_memory(x$url$url, handle = x$url$handle) : HTTP/2 stream was not closed cleanly before end of the underlying stream
问题背景
通过循环调用occ_search()遍历特定国家的物种列表获取分布数据,小数据集通常可正常运行,但物种列表较长时会触发上述错误;甚至单物种查询也偶发该错误,网络连接稳定时仍会出现问题。确定问题出在本地,但无法定位与修正,相关论坛帖子未提供有效帮助。
示例代码
species <- c("Abietinella abietina", "Acaulon casasianum", "Acaulon dertosense", "Acaulon fontiquerianum", "Acaulon mediterraneum") DK <- c(1, 0, 0, 0, 0) FO <- c(0, 0, 0, 0, 0) FI <- c(1, 0, 0, 0, 0) IS <- c(1, 0, 0, 0, 0) NO <- c(1, 0, 0, 0, 1) moss_occ <- data.frame(species, DK, FO, FI, IS, NO) species_occurrences <- list() for (i in 2:6) { country <- colnames(moss_occ)[i] occurrence <- occ_search(scientificName = moss_occ$species[which(moss_occ[[i]] == 1)], hasCoordinate = TRUE, country = colnames(moss_occ)[[i]], limit = 300) species_occurrences[[i]] <- occurrence }
会话信息
R version 4.3.0 (2023-04-21) Platform: aarch64-apple-darwin20 (64-bit) Running under: macOS Ventura 13.4 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] lubridate_1.9.2 forcats_1.0.0 stringr_1.5.0 dplyr_1.1.2 purrr_1.0.1 readr_2.1.4 [7] tidyr_1.3.0 tibble_3.2.1 ggplot2_3.4.2 tidyverse_2.0.0 rgbif_3.7.7
可能的原因及解决方法
原因分析
- 本地curl库的HTTP/2协议兼容性问题:macOS自带的curl可能在持续请求时出现流关闭异常
- 高频请求导致的服务器端流中断:循环调用未加延迟,服务器主动终止流
- rgbif包的curl连接复用机制问题:长连接未正确释放导致流异常
解决方法
- 禁用HTTP/2协议:在调用rgbif函数前强制curl使用HTTP/1.1,添加代码:
或直接设置curl的handle参数:options(rgbif_use_http2 = FALSE)library(curl) h <- new_handle() handle_setopt(h, http_version = CURL_HTTP_VERSION_1_1) # 在occ_search中指定handle occurrence <- occ_search(..., handle = h) - 添加请求延迟:在循环中加入
Sys.sleep()避免高频请求,比如:for (i in 2:6) { # 原有查询代码 Sys.sleep(1) # 每次请求间隔1秒,可根据情况调整 } - 更新依赖包:重新安装最新版本的curl和rgbif包,修复已知兼容性问题:
install.packages("curl") install.packages("rgbif") - 重启R会话:清空当前会话的连接缓存,避免残留异常连接影响后续请求
内容的提问来源于stack exchange,提问作者TFA
相关产品推荐
相关产品推荐

