Reputation: 59
I would like to know how can I capture the JSON response that outputs once the above script runs and then create another file file.json where the JSON response is stored.
require "net/http"
url = URI("https://jakunamatata.net/v1/jakunamatata-analytics/summary")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
response = https.request(request)
puts response.read_body;
// prints some json output
Upvotes: 0
Views: 108
Reputation: 102250
require 'uri'
require 'pathname'
require 'net/http'
# This url does not seem to work - tested with example.com
url = URI("https://jakunamatata.net/v1/jakunamatata-analytics/summary")
path = Pathname.new(Dir.pwd).join('output.json')
Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
request = Net::HTTP::Get.new(url)
http.request(request) do |response|
File.open(path, 'w') do |io|
response.read_body do |chunk|
io.write(chunk)
end
end
end
end
puts "File downloaded to #{path}."
This streams the download directly to disk instead of reading the response body into memory. Once you get tired of reinventing the wheel checkout the down
gem.
Upvotes: 1