将curl命令转换为Rcurl

3

我该如何转换这个命令:

curl -v -u abcdefghij1234567890:X -H "Content-Type: application/json" -X GET 'https://domain.freshdesk.com/api/v2/tickets'

如何在 Rcurl 中使用 curl 命令?

2个回答

6

curlconverter 的开发版本(devtools::install_github("hrbrmstr/curlconverter")) 现在可以转换含有认证和详细参数的 curl 命令行字符串:

将你的 URL 复制到剪贴板:

curl -v -u abcdefghij1234567890:X -H "Content-Type: application/json" -X GET 'https://domain.freshdesk.com/api/v2/tickets'

然后运行:

library(curlconverter)
req <- make_req(straighten())[[1]]

以下内容现在将复制到您的剪贴板中:
httr::VERB(verb = "GET", url = "https://domain.freshdesk.com/api/v2/tickets", 
    httr::authenticate(user = "abcdefghij1234567890", 
        password = "X"), httr::verbose(), 
    httr::add_headers(), encode = "json")

但是现在req也是一个可调用的函数。你可以通过以下方式看到:

req
## function () 
## httr::VERB(verb = "GET", url = "https://domain.freshdesk.com/api/v2/tickets", 
##     httr::authenticate(user = "abcdefghij1234567890", password = "X"), 
##     httr::verbose(), httr::add_headers(), encode = "json")

或者通过实际调用它:
req()

我通常会重新格式化函数源代码,使其更易读:
httr::VERB(verb = "GET", 
           url = "https://domain.freshdesk.com/api/v2/tickets", 
           httr::authenticate(user = "abcdefghij1234567890", password = "X"),
           httr::verbose(), 
           httr::add_headers(), 
           encode = "json")

你可以轻松地将其转换为不带命名空间的普通 GET 调用:

GET(url = "https://domain.freshdesk.com/api/v2/tickets", 
    authenticate(user = "abcdefghij1234567890", password = "X"), 
    verbose(), 
    add_headers(), 
    encode = "json"))

我们可以通过在您的示例中进行小的替换,使用经过身份验证的curl命令行来验证其是否有效:
curl_string <- 'curl -v -u abcdefghij1234567890:X -H "Content-Type: application/json" -X GET "https://httpbin.org/basic-auth/abcdefghij1234567890/X"'

make_req(straighten(curl_string))[[1]]()
## -> GET /basic-auth/abcdefghij1234567890/X HTTP/1.1
## -> Host: httpbin.org
## -> Authorization: Basic YWJjZGVmZ2hpajEyMzQ1Njc4OTA6WA==
## -> User-Agent: libcurl/7.43.0 r-curl/1.2 httr/1.2.1
## -> Accept-Encoding: gzip, deflate
## -> Accept: application/json, text/xml, application/xml, */*
## -> 
## <- HTTP/1.1 200 OK
## <- Server: nginx
## <- Date: Tue, 30 Aug 2016 14:13:12 GMT
## <- Content-Type: application/json
## <- Content-Length: 63
## <- Connection: keep-alive
## <- Access-Control-Allow-Origin: *
## <- Access-Control-Allow-Credentials: true
## <- 
## Response [https://httpbin.org/basic-auth/abcdefghij1234567890/X]
##   Date: 2016-08-30 14:13
##   Status: 200
##   Content-Type: application/json
##   Size: 63 B
## {
##   "authenticated": true, 
##   "user": "abcdefghij1234567890"
## }

2
您可以使用httr来执行以下操作:
require(httr)
GET('https://domain.freshdesk.com/api/v2/tickets',
    verbose(),
    authenticate("user", "passwd"),
    content_type("application/json"))

1
但是如果使用API密钥进行身份验证而不是用户名/密码呢? - systemdebt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接