Ruby mechanize post with header Ruby mechanize post with header ruby ruby

Ruby mechanize post with header


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'  }


ajax_headers = { 'X-Requested-With' => 'XMLHttpRequest', 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json, text/javascript, */*'}params = {'emailAddress' => 'me@my.com'}.to_jsonresponse = agent.post( 'http://example.com/login', params, ajax_headers)

The above code works for me (Mechanize 1.0) as a way to make the server think the request is coming via AJAX, but as stated in other answers it depends what the server is looking for, it will be different for different frameworks/js library combos.

The best thing to do is use Firefox HTTPLiveHeaders plugin or HTTPScoop and look at the request headers sent by the browser and just try and replicate that.


Seems like earlier that lambda had one argument, but now it has two:

agent = Mechanize.new do |agent|  agent.pre_connect_hooks << lambda do |agent, request|    request["Accept-Language"] = "ru"  endend