如何向 httparty 调用添加标头

sam*_*rts 0 ruby-on-rails httparty

我正在尝试将标头添加到我的 api 调用中

这是我目前尝试过的

api1 = HTTParty.get(URI.encode('apiurllink' + tmname + '&date=' + fromdate + ' TO ' + todate + '', :headers => {"Authorization" => "Bearer apikey"})).parsed_response
Run Code Online (Sandbox Code Playgroud)

这将返回此错误

TypeError: no implicit conversion of Hash into String
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

max*_*max 5

您的尝试引发了 TypeError,因为您将:headers => {"Authorization" => "Bearer apikey"}哈希传递给URI.encode而不是 HTTParty.get。

api1 = HTTParty.get(URI.encode('apiurllink' + tmname + '&date=' + fromdate + ' TO ' + todate + ''), :headers => {"Authorization" => "Bearer apikey"}).parsed_response
Run Code Online (Sandbox Code Playgroud)

更好的方法是使用该query选项并让 HTTParty 为您构建查询字符串。

response = HTTParty.get('/someuri', 
  query: {
    date: "#{fromdate} TO #{todate}",
    foo: "bar"
  },
  headers: {
    "Authorization" => "Bearer apikey"
  }
)
Run Code Online (Sandbox Code Playgroud)