9

我有通过 XMLHttpRequest 和服务器端脚本检查此标头的 js 页面,如何发送此标头?

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
4

4 回答 4

11

我通过网络搜索找到了这篇文章(两个月后,我知道),只是想分享另一个解决方案。

您可以使用预连接挂钩添加自定义标头,而无需猴子修补 Mechanize:

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

于 2009-10-08T07:52:45.633 回答
8
ajax_headers = { 'X-Requested-With' => 'XMLHttpRequest', 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json, text/javascript, */*'}
params = {'emailAddress' => 'me@my.com'}.to_json
response = agent.post( 'http://example.com/login', params, ajax_headers)

上面的代码对我有用(Mechanize 1.0)作为一种让服务器认为请求来自 AJAX 的方式,但正如其他答案中所述,它取决于服务器正在寻找什么,不同的框架/js库会有所不同连击。

最好的办法是使用 Firefox HTTPLiveHeaders插件或HTTPScoop并查看浏览器发送的请求标头,然后尝试复制它。

于 2010-06-30T14:18:15.750 回答
4

似乎早先 lambda 有一个参数,但现在它有两个:

agent = Mechanize.new do |agent|
  agent.pre_connect_hooks << lambda do |agent, request|
    request["Accept-Language"] = "ru"
  end
end
于 2015-05-15T18:30:49.013 回答
2

看看文档

您需要猴子补丁或派生您自己的类WWW::Mechanize来覆盖该post方法,以便将自定义标头传递给私有方法post_form

例如,

class WWW::Mechanize
  def post(url, query= {}, headers = {})
    node = {}
    # Create a fake form
    class << node
      def search(*args); []; end
    end
    node['method'] = 'POST'
    node['enctype'] = 'application/x-www-form-urlencoded'

    form = Form.new(node)
    query.each { |k,v|
      if v.is_a?(IO)
        form.enctype = 'multipart/form-data'
        ul = Form::FileUpload.new(k.to_s,::File.basename(v.path))
        ul.file_data = v.read
        form.file_uploads << ul
      else
        form.fields << Form::Field.new(k.to_s,v)
      end
    }
    post_form(url, form, headers)
  end
end

agent = WWW::Mechanize.new

agent.post(URL,POSTDATA,{'custom-header' => 'custom'}) do |page|
    p page
end
于 2009-08-25T18:39:50.637 回答