如何使用 R 中的 httr 包使用来自 Localytics 的数据提取数据?

How do I extract data using data from Localytics using the httr package in R?

我正在尝试使用 R 从 Localytics 中提取数据。这是我正在使用的代码片段:

library(httr)
localytics_url = 'https://api.localytics.com/v1/query'

r <- POST(url = localytics_url, 
      body=list(
        app_id=app_id, 
        metrics=c("users","revenue"), 
        dimensions=c("day","birth_day"), 
        conditions=list(
          day=c("between", "2015-02-01", "2015-04-01")
          )
        ),
      encode="json", 
    authenticate(key,secret),
    accept("application/json"),
    content_type("application/json")
  )
stop_for_status(r)
content(r)

但是我从内容中得到的输出是二进制的,而不是 json。我很困惑。此外,如果我尝试查看对象 'r',我会看到

Response [https://api.localytics.com/v1/query]
Date: 2015-04-14 15:18
Status: 200
Content-Type: application/vnd.localytics.v1+hal+json;type=ResultSet; charset=utf-8
Size: 1.02 MB
<BINARY BODY>

我不明白为什么它是二进制体或如何将它转换回来。谁能提供给我 help/clues?

我还使用以下代码对 Rcurl 进行了尝试:

cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")
object <- getForm(uri=localytics_url, app_id=app_id, metrics="customers", dimensions="day", conditions = toJSON(list(day=c("between", "2015-01-01", "2015-04-09"))), .opts=curlOptions(userpwd=sprintf("%s:%s", key, password))

但这会产生错误

Error in function (type, msg, asError = TRUE)  : 
SSL certificate problem: unable to get local issuer certificate

所以我有点难过。

######## 添加于 2015 年 4 月 15 日

首先感谢 MrFlick 迄今为止的帮助。我让它与

一起工作
contents=content(r, as="text")

非常感谢您的帮助。我(想我)之前曾尝试过,然后继续尝试使用 fromJSON 将其提取为 R 数据格式,但我使用的是 rjson 库,而 jsonlite 包适用于我。

感谢您的耐心等待。

这是一个完整的代码示例,说明您将如何获取数据,然后提取结果并将其作为 table 查看。

library(httr)
library(jsonlite)

response <- POST(url = 'https://api.localytics.com/v1/query', 
                 body=list(
                   app_id='APP_ID',
                   metrics='sessions',
                   conditions=list(
                     day=c("between", format(Sys.Date() - 31, "%Y-%m-%d"), format(Sys.Date() - 1, "%Y-%m-%d"))
                   ),
                   dimensions=c('new_device','day')
                 ),
                 encode="json",
                 authenticate('KEY','SECRET'),
                 accept("application/json"),
                 content_type("application/json"))

stop_for_status(response)
# Convert the content of the result to a string, you can load with jsonlite
result <- paste(rawToChar(response$content), collapse = "")
# Useful to print your result incase you are getting any errors
print(result)
# Load your data with jsonlite
document <- fromJSON(result)
# The results tag contains the table of data you need
View(document$results)