将 curl 命令转换为 Rcurl

Sim*_*aur 2 curl r rcurl

如何转换此命令:

curl -v -u abcdefghij1234567890:X -H "Content-Type: application/json" -X GET 'https://domain.freshdesk.com/api/v2/tickets'
Run Code Online (Sandbox Code Playgroud)

curl Rcurl 中的命令?

hrb*_*str 5

的开发版本curlconverterdevtools::install_github("hrbrmstr/curlconverter")可以转换curl身份验证命令行字符串和冗长现在PARAMS:

将您的 URL 复制到剪贴板:

curl -v -u abcdefghij1234567890:X -H "Content-Type: application/json" -X GET 'https://domain.freshdesk.com/api/v2/tickets'
Run Code Online (Sandbox Code Playgroud)

然后运行:

library(curlconverter)
req <- make_req(straighten())[[1]]
Run Code Online (Sandbox Code Playgroud)

以下内容现在将出现在您的剪贴板中:

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")
Run Code Online (Sandbox Code Playgroud)

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")
Run Code Online (Sandbox Code Playgroud)

或者通过实际调用它:

req()
Run Code Online (Sandbox Code Playgroud)

我通常会重新格式化函数源以使其更具可读性:

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")
Run Code Online (Sandbox Code Playgroud)

您可以轻松地将其转换为GET没有命名空间的普通调用:

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

我们可以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"
## }
Run Code Online (Sandbox Code Playgroud)