R的httr包中curl中-d参数的等价性

时间:2015-10-16 00:57:59

标签: r curl httr opencpu

我正在关注R中的official manual opencpu个包。第4.3章调用函数它使用curl来测试API:

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

,示例输出为:

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

我可以使用curl来获得类似的结果,但是当我尝试使用R中的httr包发送此http请求时,我不知道如何复制结果。这是我试过的:

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

输出是:

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.

我想我不明白-d中curl httr参数的等价性是什么,我怎样才能使其正确?

1 个答案:

答案 0 :(得分:2)

试试这个:)

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))