我正在调用一个API,需要将pfx证书链接到我的浏览器或Postman,以便调用该API。我希望以编程方式完成这个过程。是否有R代码可以让我在传递post请求时使用现有的pfx证书,或者有任何函数可以将现有的pfx证书转换为pem证书。
我曾经遇到同样的问题,我是这样解决的:
library(openssl)
library(httr)
library(usethis)
# set up openssl in .Renviron
usethis::edit_r_environ() #opens .Renviron file in Rstudio
# include this line into .Renviron file:
CURL_SSL_BACKEND="openssl"
# read your pfx certificate
cert <- openssl::read_p12(file = ".../yourCertificate.pfx", password = "yourKey")
# convert pfx to cert and key pem files to use in httr calls
openssl::write_pem(cert$cert, "my_cert.pem")
openssl::write_pem(cert$key, "my_key.pem")
# send request
GET("https://...", config = config(sslcert = "my_cert.pem", sslkey = "my_key.pem"), verbose())
截至2023年4月,get方法返回一个错误:
schannel: Failed to import cert file my_cert.pem, last error is 0x80092002
这似乎与curl 7.55.1中引入的问题有关(请参见https://stackoverflow.com/a/71496170/5956120) 在curl 8.0.1中,使用证书再次有效。
可以在R中实现解决方法:
# request via external tool curl (https://curl.se/windows/)
responseText <- system("<pathToCurl>/curl-8.0.1_6-win64-mingw/bin/curl.exe --cert my_cert.pem --key my_key.pem https://... -sS", intern = TRUE)
responseJson <- paste(responseText, collapse = '')
Error in curl::curl_fetch_memory(url, handle = handle) : schannel: Failed to import cert file
有什么理论吗?(其他行没有错误) - undefined