Download the zip file via Net :: HTTP

I am trying to download last.zip from WordPress.org using Net :: HTTP. This is what I got so far:

Net::HTTP.start("wordpress.org/") { |http| resp = http.get("latest.zip") open("a.zip", "wb") { |file| file.write(resp.body) } puts "WordPress downloaded" } 

But that only gives me a 4 kilobyte 404-page HTML page with an error (if I change the file to a.txt). I think this has something to do with the url, probably redirected somehow, but I don't know what I'm doing. I am new to Ruby.

+4
source share
2 answers

NET :: HTTP does not provide a nice way to redirect, here is a piece of code that I have been using for some time:

 require 'net/http' class RedirectFollower class TooManyRedirects < StandardError; end attr_accessor :url, :body, :redirect_limit, :response def initialize(url, limit=5) @url, @redirect_limit = url, limit end def resolve raise TooManyRedirects if redirect_limit < 0 self.response = Net::HTTP.get_response(URI.parse(url)) if response.kind_of?(Net::HTTPRedirection) self.url = redirect_url self.redirect_limit -= 1 resolve end self.body = response.body self end def redirect_url if response['location'].nil? response.body.match(/<a href=\"([^>]+)\">/i)[1] else response['location'] end end end wordpress = RedirectFollower.new('http://wordpress.org/latest.zip').resolve puts wordpress.url File.open("latest.zip", "w") do |file| file.write wordpress.body end 
+6
source

My first question is: why use Net :: HTTP or code to download something that can be done with curl or wget, which are designed to make downloading files easier?

But, since you want to load things using code, I would recommend looking at the Open-URI if you want to follow redirects. Its a standard library for Ruby and is very useful for quick HTTP / FTP access to pages and files:

 require 'open-uri' open('latest.zip', 'wb') do |fo| fo.print open('http://wordpress.org/latest.zip').read end 

I just ran this, waited a few seconds to finish, loosened the file with the latest.zip file uploaded, and expanded it into a directory containing their contents.

In addition to Open-URIs, HTTPClient and Typhoeus, among other things, make it easy to open an HTTP connection and send requests / receive data. They are very effective and deserve attention.

+8
source

Source: https://habr.com/ru/post/1344676/


All Articles