Ruby mechanize post with header

AnimalCode picture AnimalCode · Aug 25, 2009 · Viewed 13.1k times · Source

I have page with js that post data via XMLHttpRequest and server side script check for this header, how to send this header?

agent = WWW::Mechanize.new { |a|
  a.user_agent_alias = 'Mac Safari'
  a.log = Logger.new('./site.log')
}

agent.post('http://site.com/board.php',
  {
    'act' => '_get_page',
    "gid" => 1,
    'order' => 0,
    'page' => 2
  }
) do |page|
  p page
end

Answer

avout picture avout · Oct 8, 2009

I found this post with a web search (two months later, I know) and just wanted to share another solution.

You can add custom headers without monkey patching Mechanize using a pre-connect hook:

  agent = WWW::Mechanize.new
  agent.pre_connect_hooks << lambda { |p|
    p[:request]['X-Requested-With'] = 'XMLHttpRequest'
  }