【问题标题】:Ruby putting token key in requestsRuby 将令牌密钥放入请求中
【发布时间】:2019-11-07 08:11:31
【问题描述】:

我不知道如何将我的密钥放入我的请求中,以便将它们发送回来

{"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>

【问题讨论】:

    标签: ruby api noaa


    【解决方案1】:

    根据API documentation(基于您引用的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 标头的更多信息可以在this StackOverflow answer 中找到。


    附带说明,如果您没有锁定使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2017-04-05
      • 1970-01-01
      • 2014-02-17
      • 1970-01-01
      • 2015-09-25
      • 2017-12-31
      • 2015-02-20
      相关资源
      最近更新 更多