Method: Mechanize#post

Defined in:
lib/mechanize.rb

#post(uri, query = {}, headers = {}) ⇒ Object

POST to the given uri with the given query.

query is processed using Mechanize::Util.each_parameter (which see), and then encoded into an entity body. If any IO/FileUpload object is specified as a field value the “enctype” will be multipart/form-data, or application/x-www-form-urlencoded otherwise.

Examples:

agent.post 'http://example.com/', "foo" => "bar"

agent.post 'http://example.com/', [%w[foo bar]]

agent.post('http://example.com/', "<message>hello</message>",
           'Content-Type' => 'application/xml')


529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/mechanize.rb', line 529

def post(uri, query = {}, headers = {})
  return request_with_entity(:post, uri, query, headers) if String === query

  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)

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