【问题标题】:converting python POST request into R httr POST request将 python POST 请求转换为 R httr POST 请求
【发布时间】:2021-10-27 15:44:34
【问题描述】:

我在 python 中有以下代码,它返回 200 状态:

>         credentials = {
>         'grant_type': 'client_credentials',
>         'scope':'various scopes go here'
>     }

> response = requests.post('https://sample_website.com/oauth/token', 
>                         headers = {"Authorization": "Basic {}".format(signed_request), 
>                                    "Content-Type":"application/x-www-form-urlencoded"},
>                         data = credentials
>                         )

当我使用相同的 signed_request 尝试以下代码时,我收到 401 错误

credentials <- "{'grant_type': 'client_credentials','scope':'various scopes'}" 
response <- POST(url = 'https://sample_website.com/oauth/token', 
                 add_headers(
                              Authorization = signed_request,
                             'Content-Type' = 'application/x-www-form-urlencoded'
                             ),
                 accept('application/json'),
                 body = credentials, 
                 encode = 'json',
                 verbose()
                 )

我不知道我做错了什么,但我假设我没有正确格式化正文,或者我传递的标题可能有问题。

【问题讨论】:

    标签: r python-requests rest httr


    【解决方案1】:

    您的正文适用于内容类型“application/json”,但不适用于“x-www-form-urlencoded”。最简单的解决方案是传递一个列表,让 R 为您处理序列化它。

    body <- list(
        grant_type="client_credentials",
        scope="scopes"
    )
    POST(url=*,
        add_headers(Authorization=paste("Basic", signed_request)),
        body=body,
        encode="form"
    )
    

    根据您正在做的事情,您可能还想尝试httr2 包(httr 的继任者)及其内置的 OAuth 身份验证选项,其中包括client credentials

    【讨论】:

    • 感谢您的回复!当我尝试这个时,我收到以下错误:“curl::curl_fetch_memory(url, handle = handle) 中的错误:HTTP/2 流 0 未完全关闭:PROTOCOL_ERROR (err 1)。我找不到任何有用的信息这个错误
    • 再试一次xyz
    猜你喜欢
    • 2019-10-11
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多