【问题标题】:Connect to third party API with HTTParty post and get, Ruby使用 HTTParty post and get 连接到第三方 API,Ruby
【发布时间】:2016-09-19 12:13:58
【问题描述】:

我正在尝试使用 HTTParty 连接到某些 API。首先,我需要使用我的凭据登录以获取令牌,然后我需要使用此令牌来发出其他获取请求。

当我这样做时:

def get_token
    HTTParty.post(base_url + '/login', headers: { "Content-Type": "application/json" }, body: body_hash).body
end

在哪里

def body_hash
    {
        "username": "my_username",
        "apikey": "7867868yiuhi76"
    }.to_json
end

这样我就可以正确收到令牌了。

然后我尝试对 API 上的不同 url 执行 GET,如下所示:

response = JSON.parse(get_token)            
data = HTTParty.get(base_url + '/some_path', headers: { "Content-Type": "application/json", "Authorization: Bearer" => response['token'] }).body
puts data

我得到错误:

"Internal server error"

有谁知道这可能是什么问题?谢谢。

【问题讨论】:

  • 您能否提供有关您正在使用的 API 的更多信息?
  • 尝试标题为{ "Content-Type": "application/json", "Authorization": "Bearer " + response['token'] }
  • @Anthony 以这种方式更改标题行得通,谢谢!

标签: ruby api httparty


【解决方案1】:

您只是在标题上混淆了参数。假设这是 Oauth/Oauth2,您需要通过值为“Bearer token”的“Authorization”键发送。

所以对于你的例子:

HTTParty.get(base_url + '/some_path', headers: { "Content-Type": "application/json", "Authorization": "Bearer #{response['token']}" }).body

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多