Ruby - Sockets

HTTP Requests


require 'socket'

require 'openssl'


module Print

  def prnt( s="" )

    print( s + "\r\n" )

  end

end


class Object

  include Print

end

GET

uri  = URI.parse( "http://www.oxdeca.com/" )

sock = TCPSocket.new( uri.host, uri.port )

sock.prnt( "GET / HTTP/1.1" )

sock.prnt( "Host: #{uri.host}" )

sock.prnt( "Connection: close" )

sock.prnt


while( line = sock.gets )

  puts line

end


sock.close

POST multipart/form-data

uri = URI.parse( 'http://www2.oxdeca.com/app/tree' )

boundary = "#{[File.read("/dev/urandom", 33)].pack("m*").rstrip}"

data     = <<EOF

--#{boundary}

Content-Disposition: form-data; name="username"


user

--#{boundary}

Content-Disposition: form-data; name="password"


pass

--#{boundary}

Content-Disposition: form-data; name="file"; filename="some_pic.png"

Content-Type: image/png


#{File.open("some_pic.png", "rb").read}

--#{boundary}-- 

EOF


sock = TCPSocket.new( uri.host, uri.port )

sock.prnt( "POST #{uri.path} HTTP/1.1" )

sock.prnt( "Host: #{uri.host}" )

sock.prnt( "Content-Type: multipart/form-data; boundary=#{boundary}" )

sock.prnt( "Content-Length: #{data.length}" )

sock.prnt( "Connection: close" )

sock.prnt

sock.prnt( data )

sock.prnt


while( line = sock.gets )

  puts line

end


sock.close

POST application/x-www-form-urlencoded

uri  = URI.parse( 'http://www2.oxdeca.com/app/tree' )

data = URI.escape( "username=user&password=pass" )


sock = TCPSocket.new( uri.host, uri.port )

sock.prnt( "POST #{uri.path} HTTP/1.1" )

sock.prnt( "Host: #{uri.host}" )

sock.prnt( "Content-Type: application/x-www-form-urlencoded" )

sock.prnt( "Content-Length: #{data.length}" )

sock.prnt( "Connection: close" )

sock.prnt

sock.prnt( data )

sock.prnt


while( line = sock.gets )

  puts line

end


sock.close

TLS Connection

uri = URI.parse( 'https://www.google.ca/' )


tcp = TCPSocket.new( uri.host, uri.port )

ctx = OpenSSL::SSL::SSLContext.new

ssl = OpenSSL::SSL::SSLSocket.new( tcp, ctx )

ssl.sync_close = true

ssl.connect


ssl.prnt( "GET #{uri.path} HTTP/1.1" )

ssl.prnt( "Host: #{uri.host}" )

ssl.prnt( "Connection: close" )

ssl.prnt


while( line = ssl.gets )

  puts line

end


ssl.close