[英]How to read content of remote file in Ruby on Rails?
這是我的文件: http : //example.com/test.txt
我必須閱讀http://example.com/test.txt (一個 JSON 字符串)的內容並在 Ruby 中解析它
我建議使用open-uri :
require 'json'
require 'open-uri'
result = JSON.parse open('http://example.com/data.json').read
require 'net/http'
uri = URI('http://my.json.emitter/some/action')
json = Net::HTTP.get(uri)
json
將包含您從uri
獲取的 JSON 字符串。
然后閱讀這篇StackOverflow 帖子。
require 'json'
require 'open-uri'
uri = URI.parse 'http://example.com/test.txt'
json =
begin
json_file = uri.open.read
rescue OpenURI::HTTPError => e
puts "Encountered error pulling the file: #{e}"
else
JSON.parse json_file
end
open-uri
,使open
被稱為從該模塊,而不是試圖調用一個私有open
從Kernel
模塊。OpenURI
確實指示錯誤的 HTTP 狀態代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.