ruby - 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>
解决方案
根据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
推荐阅读
- postgresql - Kubernetes:Postgres 容器不断重启
- testing - 是否可以直接集成 Wiremock (JSON) + Jira + Xray?
- android - 在启动应用程序之前,世博会发生奇怪的警告火灾
- rest - 带有发布者服务帐户的发布订阅休息 API
- rest - 415 通过邮递员的表单数据添加时不支持的媒体类型
- python-3.x - 有没有办法在 TFIDF 算法中将多列作为训练数据集?
- html - 使用 'card-deck' 类,顶部和底部的牌重合
- c++ - 联合或引用作为结构成员
- python-3.x - 如何使用 BeautifulSoup 从标签中提取文本
- python - 如何只执行一次 docker 健康检查?