我熟悉API。首先,我使用Forecast API。Rails读取API响应标题
在文档中,您会找到一个标题为“响应标题”的小节。他们是什么,我如何使用它们?
此外,为了得到回应,它说你需要传递一个API密钥以及经纬度和长数据。但是API密钥不应该被保密吗?任何人都可以找出请求的内容吗?
这是我的代码:
预测模型
require 'json'
class Forecast
include HTTParty
debug_output $stdout
default_params :apiKey => 'xxxxxxxxxxxxxxxxxxxxxxxxx'
base_uri "api.forecast.io"
format :json
def self.get_weather(api,lat,long)
@response = get("/forecast/#{apiKey}/#{lat},#{long}")
end
def self.show_weather
JSON.parse(@response.body)
end
end
预测控制器
def index
@weather = Forecast.get_weather("28.5355", "77.3910")
@response = Forecast.show_weather
end
预测视图
<%= @response["currently"]["summary"] %>
'default_params'会将参数添加到URL中 - 在这种情况下,您的网址将以'?apiKey = abcde'结尾。在'self.get_weather'中,'apiKey'将是未定义的。 –