我熟悉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'將是未定義的。 –