2011-06-04

How to download a https:// page in Ruby 1.8

This blog post shows an example low-level implementation of downloading a https:// page in Ruby 1.8. The reason why is this blog post was born is that the documentation of the openssl and socket Ruby modules didn't contain a working end-to-end example.

#! /usr/bin/ruby1.8
require 'socket'
require 'openssl'
# Returns a HTTP response header + body.
def download_https(host, port, suburl)
  s = TCPSocket.new('www.gmail.com', 443)
  begin
    ss = OpenSSL::SSL::SSLSocket.new(s)
    begin
      ss.connect
      ss << "GET #{suburl} HTTP/1.0\r\nHost: #{host}:#{port}\r\n\r\n"
      ss.flush
      ss.read
    ensure
      ss.close
    end
  ensure
    s.close
  end
end
p download_https('www.gmail.com', 443, '/')

Please note that this doesn't check the authenticity of the server, i.e. it will happily and silently accept self-signed certificates.

1 comment: