Search code examples
rcurlhttropencpu

equivalence of -d parameter in curl in httr package of R


I'm following the official manual of opencpu package in R. In chapter 4.3 Calling a function It uses curl to test API:

curl http://your.server.com/ocpu/library/stats/R/rnorm -d "n=10&mean=100"

and the sample output is:

/ocpu/tmp/x032a8fee/R/.val
/ocpu/tmp/x032a8fee/stdout
/ocpu/tmp/x032a8fee/source
/ocpu/tmp/x032a8fee/console
/ocpu/tmp/x032a8fee/info

I can use curl to get similar result, but when I try to send this http request using httr package in R, I don't know how to replicate the result. Here is what I tried:

resp <- POST(
  url = "localhost/ocpu/library/stats/R/rnorm",
  body= "n=10&mean=100"
)
resp

the output is:

Response [HTTP://localhost/ocpu/library/stats/R/rnorm]
  Date: 2015-10-16 00:51
  Status: 400
  Content-Type: text/plain; charset=utf-8
  Size: 30 B
No Content-Type header found.

I guess I don't understand what's the equivalence of curl -d parameter in httr, how can I get it correct?


Solution

  • Try this :)

    library(httr)
    library(jsonlite)
    
    getFunctionEndPoint <- function(url, format) {
        return(paste(url, format, sep = '/'))
    }
    
    resp <- POST(
        url = getFunctionEndPoint(
            url = "https://public.opencpu.org/ocpu/library/stats/R/rnorm",
            format = "json"),
        body = list(n = 10, mean = 100), 
        encode = 'json')
    
    fromJSON(rawToChar(resp$content))