How to set the Referer header before loading a page with Ruby mechanize?

Marcos picture Marcos · Apr 12, 2012 · Viewed 10.4k times · Source

Is there a straightforward way to set custom headers with Mechanize 2.3?

I tried a former solution but get:

$agent = Mechanize.new
$agent.pre_connect_hooks << lambda { |p|
  p[:request]['Referer'] = 'https://wwws.mysite.com/cgi-bin/apps/Main'
} 

# ./mech.rb:30:in `<main>': undefined method `pre_connect_hooks' for nil:NilClass (NoMethodError)

Answer

pguardiario picture pguardiario · Sep 1, 2012

The docs say:

get(uri, parameters = [], referer = nil, headers = {}) { |page| ... }

so for example:

agent.get 'http://www.google.com/', [], agent.page.uri, {'foo' => 'bar'}

alternatively you might like:

agent.request_headers = {'foo' => 'bar'}
agent.get url