Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby mechanize post with header

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
like image 212
AnimalCode Avatar asked Aug 25 '09 10:08

AnimalCode


3 Answers

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"
  end
end
like image 79
Nakilon Avatar answered Nov 15 '22 23:11

Nakilon


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

like image 36
avout Avatar answered Nov 15 '22 23:11

avout


ajax_headers = { 'X-Requested-With' => 'XMLHttpRequest', 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json, text/javascript, */*'}
params = {'emailAddress' => '[email protected]'}.to_json
response = 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.

like image 20
Kris Avatar answered Nov 16 '22 01:11

Kris