这是我的文件:http://example.com/test.txt
我需要读取http://example.com/test.txt的内容(一个JSON字符串),并在Ruby中解析它。
这是我的文件: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
OpenURI::HTTPError
提供的信息比Net::HTTP
返回的错误信息要少得多。我已经有一段时间没有使用OpenURI
了,但如果我记得正确,它甚至没有告诉我状态码,所以404被视为与500相同。 - mauriceOpenURI::HTTPError
包装的404示例 - 404 Not Found
。 - Dmitrii Kharlamovrequire '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
,而不是尝试从Kernel
模块调用私有的open
。OpenURI
确实指示错误的HTTP状态代码。