Created
January 28, 2014 06:52
-
-
Save teeceepee/8663290 to your computer and use it in GitHub Desktop.
HTTP download
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'uri' | |
#TestUrl = 'http://ftp.gnu.org/gnu/autoconf/autoconf-2.56.tar.gz' | |
TestUrl = 'http://googletest.googlecode.com/files/gtest-1.7.0.zip' | |
class Response | |
attr_reader :content_length | |
def initialize(socket) | |
parse_header(socket) | |
parse_content_length | |
parse_body(socket) | |
end | |
def parse_header(socket) | |
@header = '' | |
while [email protected] "\r\n\r\n" | |
line = socket.readline | |
@header << line | |
end | |
end | |
def parse_content_length | |
l = @header.lines.select { |l| l.match /content-length/i }.first | |
@content_length = l.split(":")[1].strip.to_i | |
end | |
def parse_body(socket) | |
@body = '' | |
@body << socket.read(@content_length) | |
end | |
def header | |
@header | |
end | |
def data | |
@body | |
end | |
end | |
class Request | |
UserAgents = ["Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0",] | |
def initialize(uri) | |
@uri = uri | |
@http_version = '1.1' | |
@request_line = "GET #{@uri.path} HTTP/#{@http_version}\r\n" | |
@host = "Host: #{@uri.host}\r\n" | |
@end_line = "\r\n" | |
@binary = @request_line + @host + @end_line | |
end | |
def to_binary | |
@binary | |
end | |
end | |
def download(url) | |
uri = URI(url) | |
sock = TCPSocket.new uri.host, uri.port | |
sock.send Request.new(uri).to_binary, 0 | |
puts 'Read from socket' | |
response = Response.new sock | |
puts "Content-Length: #{response.content_length} ==============" | |
puts response.header | |
filename = File.basename(uri.path) | |
File.open(filename, 'wb') do |f| | |
f.write response.data | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment