"错误请求"使用R将JSON文件上传到API时,Content-Type被视为txt / html

时间:2017-09-17 17:53:42

标签: json r api

我遇到了一个问题,在尝试使用R内部的API时我似乎无法解决这个问题。所以我希望你们能在这里给我一些提示&#39错了。

我尝试做的是让Botometer API(https://market.mashape.com/OSoMe/botometer)可以从R内部访问。我知道有一个Python包,但是因为我只是学过RI认为让它与R一起运行很有趣。我已经编写了一个函数来收集有关用户的所有相关信息,并将其解析为一个应该具有格式的json文件API接受。但是,在尝试上传json数据时,我从API获得以下结果:

Response [https://osome-botometer.p.mashape.com/2/check_account]
  Date: 2017-09-17 17:19
  Status: 400
  Content-Type: text/html; charset=UTF-8
  Size: 192 B
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this ser...

但是,当使用API​​开发人员提供的示例有效负载时,我得到了正确的结果:

Response [https://osome-botometer.p.mashape.com/2/check_account]
  Date: 2017-09-17 15:59
  Status: 200
  Content-Type: application/json
  Size: 298 B
{
  "categories": {
    "content": 0.39, 
    "friend": 0.54, 
    "network": 0.44, 
    "sentiment": 0.33, 
    "temporal": 0.56, 
    "user": 0.24
  }, 
  "scores": {
...

现在出现错误的最可能原因似乎是Content-Type不被视为我的请求的JSON,因此服务器不接受(如果我错了,请纠正我)。

这是我用来制作JSON文件的代码(使用jsonlite和rtweet):

Tweetson <- function(x) {
  user.json <- lookup_users(x, token = twitter_token, parse = FALSE) %>% toJSON(null = "null", na = "null", pretty = TRUE)
  timeline.json <- get_timeline(x, token = twitter_token, parse = FALSE, n = 200) %>% toJSON(null = "null", na = "null", pretty = TRUE)
  mentions.json <- search_tweets(paste("@",x), token = twitter_token, parse = FALSE, n = 100) %>% toJSON(null = "null", na = "null", pretty = TRUE)
  payload <- paste("{\n\"timeline\":", timeline.json, ",\"mentions\":", mentions.json, ",\"user\":", user.json, "\n}")
  write(payload, "testload.json")
}

然后我将文件上传到API,遇到上述问题。 (稍后将在一个函数中完成,因为问题似乎在于制作json文件,但是,我没有在此处包括其余部分)。 检查外部json查看器或isValidJSON()函数,似乎&#34; testload.json&#34;是一个有效的json文件,那么API如何不同意并拒绝我的请求?我是否忘记了json文件的工作中显而易见的事情?

哦,还有一件事我无法弄清楚(这可能有一个明显的解决方案):我如何让R向我展示API的完整答案,而不是如上所述限制它?

我对R和整个编码都很新,所以任何帮助都会非常感激!

编辑:这是我用来向API发出请求的代码:

    POST(botometerURL,
              add_headers(
              "X-Mashape-Key"=MashapeKey,
              "Content-Type" = "application/json",
              "Accept" = "application/json"),
            body=upload_file("testload.json"),  
            encode = "json")

如上所述,这可以很好地处理示例有效负载,但是使用我自己生成的有效负载会失败。

0 个答案:

没有答案