Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby code to download a file from url with basic authentication

I am new to ruby and I am learning it.

I am looking to download a file from one url(eg: https://myurl.com/123/1.zip), with basic authentication. I tried to execute the following ruby script, from windows command prompt..

require 'net/http'

uri = URI('https://myurl.com/123/1.zip')


Net::HTTP.start(uri.host, uri.port,
  :use_ssl => uri.scheme == 'https', 
  :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|

  request = Net::HTTP::Get.new uri.request_uri
  request.basic_auth '[email protected]', 'John123'

  response = http.request request # Net::HTTPResponse object

  puts response

  puts response.body
end

When I executed the script, I see no errors but the file isn't downloaded. Could you please kindly correct my code

like image 819
chef dev Avatar asked Dec 23 '22 17:12

chef dev


2 Answers

You can try this:

require 'open-uri'

File.open('/path/your.file', "wb") do |file|
    file.write open('https://myurl.com/123/1.zip', :http_basic_authentication => ['[email protected]', 'John123']).read
end
like image 182
Divya Sharma Avatar answered May 08 '23 10:05

Divya Sharma


You were almost there. Just make use of ruby's send_data method

require 'net/http'

uri = URI('https://myurl.com/123/1.zip')

Net::HTTP.start(uri.host, uri.port,
  :use_ssl => uri.scheme == 'https', 
  :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|

  request = Net::HTTP::Get.new uri.request_uri
  request.basic_auth '[email protected]', 'John123'

  http.request(request) do |response|
    send_data(response.body, filename: 'set_filename.pdf')
  end
end
like image 26
Vamsi Krishna Avatar answered May 08 '23 09:05

Vamsi Krishna