簡體   English   中英

如何在 Ruby on Rails 中讀取遠程文件的內容?

[英]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
  1. 我具體包括open-uri ,使open被稱為從該模塊,而不是試圖調用一個私有openKernel模塊。
  2. 我故意解析 URL 以避免安全風險 - https://rubydoc.info/gems/rubocop/RuboCop/Cop/Security/Open
  3. 與上面指出的一些評論者不同, OpenURI確實指示錯誤的 HTTP 狀態代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM