简体   繁体   English

如何在 Ruby on Rails 中读取远程文件的内容?

[英]How to read content of remote file in Ruby on Rails?

here my file: http://example.com/test.txt这是我的文件: http : //example.com/test.txt

i have to read content of http://example.com/test.txt (a JSON string) and parse it in Ruby我必须阅读http://example.com/test.txt (一个 JSON 字符串)的内容并在 Ruby 中解析它

I would suggest using open-uri :我建议使用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 will contain the JSON string you fetched from uri . json将包含您从uri获取的 JSON 字符串。

Then read this StackOverflow post.然后阅读这篇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. I specifically include open-uri , so that open is called from that module instead of attempting to call a private open from the Kernel module.我具体包括open-uri ,使open被称为从该模块,而不是试图调用一个私有openKernel模块。
  2. I intentionally parse the URL to avoid a security risk - https://rubydoc.info/gems/rubocop/RuboCop/Cop/Security/Open我故意解析 URL 以避免安全风险 - https://rubydoc.info/gems/rubocop/RuboCop/Cop/Security/Open
  3. Unlike some commenters pointed out above, OpenURI does indicate the HTTP status code of an error.与上面指出的一些评论者不同, OpenURI确实指示错误的 HTTP 状态代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM