如何使用标题`postForm`

时间:2014-06-24 12:50:14

标签: r rcurl

如何使用POST构建此RCurl http请求?

POST http://localhost:7474/db/data/index/node/
Accept: application/json; charset=UTF-8
Content-Type: application/json
{
  "name" : "node_auto_index",
  "config" : {
    "type" : "fulltext",
    "provider" : "lucene"
  }
}

我在R中提出了这个问题:

require(RCurl)
httpheader=c(Accept="application/json; charset=UTF-8",
             "Content-Type"="application/json")
x = postForm("http://localhost:7474/db/data/index/node/",
             .opts=list(httpheader=httpheader),
             name="node_auto_index",
             config=c(type="fulltext", provider="lucene")
)

这句话是否正确?

2 个答案:

答案 0 :(得分:4)

使用httr更容易:

library(httr)
POST("http://localhost:7474/db/data/index/node/",
  accept_json(),
  add_headers("Content-Type" = "application/json"),
  body = toJSON(list(
    "name" = "node_auto_index",
    "config" = list(
      "type" = "fulltext",
      "provider" = "lucene"
    )
  ))
)

使用开发版本(install_github("hadley/devtools")

)会更容易
POST("http://localhost:7474/db/data/index/node/",
  accept_json(),
  body = list(
    "name" = "node_auto_index",
    "config" = list(
      "type" = "fulltext",
      "provider" = "lucene"
    )
  ),
  encode = "json"
)

答案 1 :(得分:2)

我猜你需要一个更像这样的电话

library(RJSONIO)
library(RCurl)

jsonbody <- toJSON(list(name="node_auto_index", 
    config=list(type="fulltext",provider="lucene")))

httpheader <- c(Accept="application/json; charset=UTF-8",
    "Content-Type"="application/json")
x <- postForm("http://localhost:7474/db/data/index/node/",
    .opts=list(httpheader=httpheader,
    postfields=jsonbody))

甚至

h <- basicTextGatherer()
x <- curlPerform(url="http://localhost:7474/db/data/index/node/",
    httpheader=c(Accept="application/json; charset=UTF-8",
    "Content-Type"="application/json"),
    writefunction = h$update,
    postfields=jsonbody)

据我所知,RCurl库不能为您制作JSON,因此您需要自己构建JSON(此处使用RJSONIO包)。在这里,我们使用postfields选项传递数据。

此外,网站http://requestb.in/可用于创建一个网址,您可以在其中发布数据并查看测试请求