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

18,784

Solution 1

I would suggest using open-uri:

require 'json'
require 'open-uri'
result = JSON.parse open('http://example.com/data.json').read

Solution 2

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.

Then read this StackOverflow post.

Share:
18,784
Leonardo
Author by

Leonardo

Updated on July 10, 2022

Comments

  • Leonardo
    Leonardo almost 2 years

    here my file: http://example.com/test.txt

    i have to read content of http://example.com/test.txt (a JSON string) and parse it in Ruby

  • maurice
    maurice about 8 years
    I have found that OpenURI::HTTPError gives much less information than the errors returned by Net::HTTP. It's been a while since I stopped using OpenURI, but if I recall correctly, it didn't even tell me the status code, so 404 was treated the same as 500.
  • Dmitrii Kharlamov
    Dmitrii Kharlamov almost 3 years
    @maurice, it does in fact tell you the HTTP status code, here's an example of a 404 wrapped by OpenURI::HTTPError - 404 Not Found