【问题标题】:How do I translate my CLI curl POST api create user call to R httr?如何将我的 CLI curl POST api 创建用户调用转换为 R httr?
【发布时间】:2020-03-22 16:20:33
【问题描述】:

我想add users to groups on nextcloud via their API

通过运行以下请求,我成功地将一个用户 (ncuser) 从我的 CLI 添加到 Group1 和 Group2:

curl -X POST https://adminuser:'admin pass phrase'@cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups -d groupid="Group1" -d groupid="Group2" -H "OCS-APIRequest: true"

回复如下:

<?xml version="1.0"?>
<ocs>
 <meta>
  <status>ok</status>
  <statuscode>100</statuscode>
  <message>OK</message>
  <totalitems></totalitems>
  <itemsperpage></itemsperpage>
 </meta>
 <data/>
</ocs>

我尝试使用以下代码在 Rstudio 中运行请求:

library(curl)
library(httr)

call <- POST("https://adminuser:'admin pass phrase'@cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups",
     body = list(groupid = "Group1", groupid = "Group2"),
     add_headers('OCS-APIRequest' = "true", 'Content-Type' = "application/x-www-form-urlencoded"))

但这并不成功。我在 R 中得到这个响应:

Response [https://adminuser:'admin pass phrase'@cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups]
  Date: 2020-03-22 15:43
  Status: 401
  Content-Type: application/json; charset=utf-8
  Size: 140 B

这是我的 R POST 请求的内容:

content(call)

$ocs
$ocs$meta
$ocs$meta$status
[1] "failure"

$ocs$meta$statuscode
[1] 997

$ocs$meta$message
[1] "Current user is not logged in"

$ocs$meta$totalitems
[1] ""

$ocs$meta$itemsperpage
[1] ""


$ocs$data
list()

似乎我无法通过 POST() url 登录,需要以其他方式添加 adminuser 和“管理员密码”,但我不确定如何。

另外,the nextcloud API documentation 声明 OCS-APIRequest 和内容类型需要在标头中指定,但我不确定我是否正确。

对 OCS 端点的所有调用都需要将 OCS-APIRequest 标头设置为 true。

所有 POST 请求都需要 Content-Type: application/x-www-form-urlencoded 标头。 (注意:像 cURL 这样的一些库会自动设置此标头,而其他库则需要显式设置标头。)

我的 POST 请求应该如何用 R 编写,以便我可以成功地将我的 nextcloud 用户添加到组中?

任何帮助将不胜感激。

【问题讨论】:

    标签: r curl post httr


    【解决方案1】:

    不妨试试

    call <- POST("https://cloud.example.org/ocs/v1.php/cloud/users/ncuser/groups",
         body = list(groupid = "Group1", groupid = "Group2"),
         add_headers('OCS-APIRequest' = "true"),
         authenticate("adminuser", "admin pass phrase"),
         encode = "form")
    

    这将确保POST 正确编码正文并更安全地传递用户名/密码。您也可以尝试添加verbose() 以获得更多输出。如果没有可用于测试的某种 reproducible example,要帮助您将不会很容易。

    【讨论】:

    • 请求通过,但它只将用户添加到 Group2。我试过body = list(groupid = c("Group1", "Group2"),但我得到了这个错误:Error in vapply(elements, encode, character(1)) : values must be length 1, but FUN(X[[1]]) result is length 2
    • 我很乐意为您提供一个可重现的示例,但我无法访问可以授予个人 API 令牌访问权限的 nextcloud 服务器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多