ruby進行http請求頭設定及獲取

上帝De助手發表於2013-10-09
#encoding: utf-8

#http://www.ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html   ##官方樣例

require 'net/http'
http = Net::HTTP.new('www.baidu.com', 80)
http.use_ssl = false
path = '/'


resp, data = http.get(path)
cookies = resp.response['set-cookie'].split(', ')  #獲取cookies
puts cookies


headers = {   ##定義http請求頭資訊
  'Cookie' => cookies[0].split('; ')[0],
  'Referer' => 'http://qa.dangdang.com',
  'Content-Type' => 'application/x-www-form-urlencoded'
}
resp, data = http.get(path, headers)


puts 'Code = ' + resp.code    ##請求狀態碼
puts 'Message = ' + resp.message  
resp.each {|key, val| puts key + ' = ' + val}  ##遍歷所有http響應頭




相關文章