【问题标题】:Authorization Error 401 using GET in httr (R).在 httr (R) 中使用 GET 的授权错误 401。
【发布时间】:2015-08-16 05:38:19
【问题描述】:

我正在尝试使用 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 中做错了什么,或者你能给我任何提示吗?这对您来说是不可重现的,因为令牌已过期,我无法共享它。 会不会是授权中的空格?授权="承载935845d8fc1124757e66ce04d2c75d0"? R 中 get 调用的详细输出中是否有任何提示?

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢你一百遍。这很有意义,而且很有魅力!
    猜你喜欢
    • 2016-04-24
    • 1970-01-01
    • 2017-12-20
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多