【发布时间】:2018-09-28 10:30:03
【问题描述】:
我正在尝试使用以下方法将一些数据点发送到 Web api。 (不确定是否共享密钥,所以我省略了一部分)。
library(jsonlite)
library(httr)
url = "https://api.marketcycles.online/api/CycleScanner"
t <- 1:101
val <- 2*sin(2*pi*t/25) + 5*cos(2*pi*t/50)
val[1:3]
body.list <- list(datapoints = val)
query.list <- list(api_Key = "wtt****")
res <- POST(url = url, query = query.list, body = body.list,
encode = "json")
a <- content(res, as = "text")
b <- fromJSON(a)
b[[2]]
这会导致错误“对象引用未设置为对象的实例”
以下 curl 命令有效(我已经删除了大部分数据点)
curl -X POST --header 'Content-Type: application/json' \
--header 'Accept: application/json' \
-d '[5.458,5.8064,6.018,....5,5.458]' \
'https://api.marketcycles.online/api/CycleScanner?api_Key=wtt****'
关于使 POST 命令正常工作的任何建议?
感谢 hrbrmstr 的回答。非常感激。 我尝试了以下
httr::POST(
url = "https://api.marketcycles.online/api/CycleScanner",
httr::content_type_json(),
httr::accept_json(),
encode = "json",
body = jsonlite::toJSON(val),
query = list(
amplitudeMulti = "1.0",
bartelsLimit = "49",
minCycleLength = "5",
maxCycleLength = "300",
sortByStrength = "true",
includeSpectrum = "false",
humanReadableText = "false",
api_Key = "wtt****")
)
无论有无 content_type_jason() 行,在两种情况下都收到以下错误
b[[1]]
[1] "The request contains an entity body but no Content-Type header. The
inferred media type 'application/octet-stream' is not supported for this
resource."
b[[2]]
[1] "No MediaTypeFormatter is available to read an object of type
'Double[]' from content with media type 'application/octet-stream'."
b[[3]]
[1] "System.Net.Http.UnsupportedMediaTypeException"
据我了解,当正文是列表时, encode() 提供列表元素的格式。我不清楚当它不是时该怎么做。我查看了 httr 源代码,有一个未记录的函数 body_config,但不确定在 POST 命令中使用它。有什么解决这个问题的建议吗?
【问题讨论】: