如何正确使用 API 数据请求的请求标头? [英] How correctly use request header with API data requests?

查看:40
本文介绍了如何正确使用 API 数据请求的请求标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 httr 包(完全没有 API 连接经验)找到通过 R 连接到 Appannie 的 API 的方法.API 需要包含请求标头来自 appannie 网站的引文:注册一个 App Annie 帐户并生成一个 API 密钥.将此键添加到您的请求标头中,如下所示:
授权:承载 ''
引用

I'm trying to find the way to connect to Appannie's API with R using the httr package (have no experience with API connection at all). The API requires to include the request header Citation from appannie's site: Register an App Annie account and generate an API key. Add this key to your request header as follows:
Authorization: Bearer ''
citation over

我写的代码是这样的

query <- "http://api.appannie.com/v1/accounts/1000/sales?break_down=application+dat
&start_date=2012-01-01
&end_date=2012-02-01
&currency=USD
&countries=US
&page_index=1"
getdata<-GET(url=query, add_headers("Authorization: bearer 811b..."))

命令 http_status(getdata) 显示客户端错误:(401) 未经授权"有人可以帮助我吗,我做错了什么?

the command http_status(getdata) shows me "client error: (401) Unauthorized" can someone please help me with it, what do I do wrong?

推荐答案

您没有正确指定标题.add_headers(...) 需要一个命名列表.

You are not specifying the header correctly. add_headers(...) requires a named list.

library(httr)    # for GET(...)
library(rjson)   # for fromJSON(...)
query <- "https://api.appannie.com/v1/accounts/1000/sales?break_down=application+dat&start_date=2012-01-01&end_date=2012-02-01&currency=USD&countries=US&page_index=1"
getdata<-GET(url=query, add_headers(Authorization="bearer <your api key>"))
fromJSON(content(getdata,type="text"))
# $code
# [1] 403
# 
# $error
# [1] "Invalid connection account"

这有效",因为我没有收到 401 错误.就我而言,帐户 1000 不存在.

This "works" in the sense that I don't get the 401 error. In my case the account 1000 does not exist.

关于评论中的 http/https 问题,http 已弃用,自 2014-04-01 起不再被接受,因此您不妨开始使用 https.

Regarding the http/https issue from the comment, http is despreciated and will no longer be accepted as of 2014-04-01, so you might as well start using https.

这篇关于如何正确使用 API 数据请求的请求标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆