在httr(R)中使用GET的授权错误401。

时间:2015-08-16 05:38:19

标签: r python-3.x get postman httr

我正在尝试使用httr在R中进行GET调用,并且我一直收到授权401错误。 R代码:

    testfunction2 <- function()
    {
        set_config(verbose())
        locus_url <- "https://api.locusenergy.com/v3/clients/5599"
        r <- GET(url = "https://api.locusenergy.com/v3/clients/5599",
                 query=list(authorization="Bearer c935845d8fc1124757e66ce04d2c75d0"),
         Accept="application/json")
    }

结果:

> print(testfunction2())
-> GET /v3/clients/5599
    authorization=Bearer%20c935845d8fc1124757e66ce04d2c75d0 HTTP/1.1
-> User-Agent: libcurl/7.39.0 r-curl/0.9.1 httr/1.0.0
-> Host: api.locusenergy.com
-> Accept-Encoding: gzip, deflate
-> Cookie: AWSELB=D91FBFE1087EF6EBC125A126777051237474A8A060B6095B8E3C16151308453F8556B2A2E90CB2178F365FAA8AA8C29B124D15CA3EB859CFE615428E8D55C393ABB5B436BF
-> Accept: application/json, text/xml, application/xml, */*
-> 
<- HTTP/1.1 401 Unauthorized
<- Content-Type: application/json
<- Date: Sun, 16 Aug 2015 05:02:27 GMT
<- Server: Apache-Coyote/1.1
<- transfer-encoding: chunked
<- Connection: keep-alive
<-

我希望它返回200个代码(而不是401,这意味着授权错误。)

我知道令牌是正确的,因为如果我使用Postman(谷歌加载项)和Python,它是有效的。令牌不适合你,因为我改变了它,因为我无法分享它。

Python代码:

    import http.client
    conn = http.client.HTTPSConnection("api.locusenergy.com")
    headers = {
        'authorization': "Bearer 935845d8fc1124757e66ce04d2c75d0"
        }
    conn.request("GET", "/v3/clients/5599", headers=headers)
    res = conn.getresponse()
    data = res.read()
    print(data)

来自Python的结果

    b'{"statusCode":200,"partnerId":4202,"tz":"US/Arizona","firstName":"xxx","lastName":"xxxx","email":"xxxx@aol.com","id":5599}'

所以,问题是我在R中做错了什么或者你能给我任何提示吗?这将无法为您重现,因为令牌已过期而我无法共享。 这可能是授权中的空间吗? authorization =“Bearer 935845d8fc1124757e66ce04d2c75d0”? R中的get调用的详细输出中是否有任何提示?

供参考,这是网站的API页面: https://developer.locusenergy.com/

该站点需要OAUTH2身份验证才能返回令牌。我没有包含该代码,但我验证了令牌适用于Python和Postman。

1 个答案:

答案 0 :(得分:2)

现在,您将在httr代码的查询字符串中传递授权值,而不是像在python代码中那样在http标头中传递。而是使用

GET(url = "https://api.locusenergy.com/v3/clients/5599",
    accept_json(),
    add_headers(Authorization="Bearer c935845d8fc1124757e66ce04d2c75d0")
)