Wednesday, May 4, 2011

Sending HTTP requests and headers

Here is the first example on how to send extra HTTP headers in a HTTP request and then checking the response. In this example Cookie header is sent in a GET request:

require "net/http"
require "net/https"
require "uri"
  
# HTTP GET without proxy and SSL
res = Net::HTTP.start($host, 80) {|http|

  http.get2('/mysite/index.html',{'Cookie' => $cookie})
}
    

# HTTP GET with proxy, but without SSL
http = Net::HTTP::Proxy($proxyhost, $proxyport).new($host, 80)
res = http.get2('/mysite/index.html',{'Cookie' => $cookie})

# HTTP GET with proxy and SSL
http = Net::HTTP::Proxy($proxyhost, $proxyport).new($host, 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = http.get2('/mysite/index.html',{'Cookie' => $cookie})

# HTTP response body
$httpresponse = res.body

Here is the second example on how to send HTTP requests and checking the response:

response = sendHttpRequest $myurl,$mypostdata,{'Cookie' => 'xxx'}
puts "Response code:\n" + response[:code].to_s
puts "Response code description:\n" + response[:name].to_s
puts "Response body:\n" + response[:body].to_s
puts "Response headers:\n"+response[:headers].to_s

def sendHttpRequest requrl, postdata=nil, headers=nil

  proxyhost = "xxx"
  proxyport = "yyy"

  url = URI.parse(requrl)
  resheaders=""
  myurl = "/"
  if (not (url.path == nil or url.path == ""))
    myurl = url.path
  end
  if (not (url.query == nil or url.query == ""))
    myurl = myurl+"?"+url.query
  end
  if (not (url.fragment == nil or url.fragment == ""))
    myurl = myurl+"#"+url.fragment
  end

  ht = Net::HTTP.Proxy(proxyhost, proxyport).new(url.host, url.port) 
  if (requrl.to_s.include? "https")   
      ht.use_ssl = true
      ht.verify_mode = OpenSSL::SSL::VERIFY_NONE     
  else
      ht.use_ssl = false
  end
 
  begin
    ht.start
  rescue
    sleep 5
    ht.start
  end

  if (postdata.to_s == "nil" || postdata.to_s == "")
        if (headers.to_s == "nil") or (headers.to_s == "")
            res,datax = ht.request_get(myurl)
        else
            res,datax = ht.request_get(myurl,headers)
        end


        ht.finish     
        res.each_header() { |key,value| resheaders=resheaders+key+": "+value+"\n" }
        return {:name => res.class, :code => res.code, :body => datax, :headers => resheaders}
  end
 
  if (headers.to_s == "nil") or (headers.to_s == "")
        res,datax = ht.request_post(myurl, postdata)
  else
        res,datax = ht.request_post(myurl, postdata,headers)
  end
  ht.finish                 
     
  res.each_header() { |key,value| resheaders=resheaders+key+": "+value+"\n" }
  return {:name => res.class, :code => res.code, :body => datax, :headers => resheaders}


end 

No comments:

Post a Comment