首页 > 解决方案 > Ruby 将令牌密钥放入请求中

问题描述

我不知道如何将我的密钥放入我的请求中,以便将它们作为

{"status"=>"400", "message"=>"Token parameter is required."}

这是我一直在使用的代码

require 'net/http'
require 'json'

token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
uri = URI(url)
response = Net::HTTP.get(uri)
response.authorization = token
puts JSON.parse(response)

我尝试了一些我在互联网上找到的不同的东西,但它们都只是给出错误

undefined method `methodname' for #<String:0x00007fd97519abd0>

标签: rubyapinoaa

解决方案


根据API 文档(基于您引用的 URL),您需要在名为token.

因此,您可能应该尝试以下的一些变体(未经测试的代码):

token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
uri = URI(url)
request = Net::HTTP::Get.new(uri)
request['token'] = token
response = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(request)
end

Net:HTTP有关标头的更多信息,请参阅此 StackOverflow 答案


附带说明一下,如果您没有锁定使用Net::HTTP,请考虑切换到更友好的 HTTP 客户端,也许是HTTParty。然后,完整的代码如下所示:

require 'httparty'

token = 'YiwwVvywLngtPT***************'
url = 'https://www.ncdc.noaa.gov/cdo-web/api/v2/stations?locationid=FIPS:23&limit=5&sortfield=mindate'
response = HTTParty.get url, headers: { token: token }

puts response.body

推荐阅读