R httr:使用curl -d POST POST JSON

时间:2016-04-27 14:56:38

标签: json r curl httr

我必须使用curl将数据发布到API;命令如下所示:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Basic code" -H "Cache-Control: no-cache" -H "Postman-Token: token" -d '[JSON data]' "URL" -v

我想用R做这个,因为JSON数据是在R中生成的。 这是我尝试过的,使用包httr:

     POST(url = "url",
          accept_json(),
          add_headers("Content-Type" = "application/json", "Authorization" = "Basic code",
         "Postman-Token" ="token", "Cache-Control" = "no-cache"),
          body = toJSON(list(text = "Hello World!", level = "Noob")),
          encode = "json",
          authenticate(user = "user", password = "pwd"),
          verbose() )

它返回:

POST url HTTP/1.1
-> Host: host
-> User-Agent: libcurl/7.43.0 r-curl/0.9.6 httr/1.1.0
-> Accept-Encoding: gzip, deflate
-> Accept: application/json
-> Content-Type: application/json
-> Authorization: Basic code
-> Postman-Token: token
-> Cache-Control: no-cache
-> Content-Length: 45
-> 
>> {
>>  "text": "Hello World!",
>> "level": "Noob" 
>> }

HTML错误400 Bad Request。

我的印象是body(-d属性)在某种程度上是错误的,但我无法弄清楚如何正确地做到这一点。

任何人都可以帮助我吗?

0 个答案:

没有答案