问题
How to construct this POST
http request using RCurl
?
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"
}
}
I've come up with this in 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")
)
Is this statement correct?
回答1:
This is a little easier with 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"
)
))
)
It's even easier with the dev version (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"
)
回答2:
I would guess you need a call more like this
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))
or even
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)
As far as I know the RCurl library won't make JSON for you, so you need to build the JSON yourself (here using the RJSONIO package). Here we pass the data using the postfields
option.
Also, the website http://requestb.in/ can be useful to create a URL where you can post data and see the request for testing
来源:https://stackoverflow.com/questions/24387119/how-to-postform-with-header