Method: Gem::Net::HTTPHeader#set_form_data
- Defined in:
- lib/rubygems/net-http/lib/net/http/header.rb
#set_form_data(params, sep = '&') ⇒ Object Also known as: form_data=
Sets the request body to a URL-encoded string derived from argument params, and sets request header field 'Content-Type' to 'application/x-www-form-urlencoded'.
The resulting request is suitable for HTTP request POST or PUT.
Argument params must be suitable for use as argument enum to URI.encode_www_form.
With only argument params given, sets the body to a URL-encoded string with the default separator '&':
req = Gem::Net::HTTP::Post.new('example.com')
req.set_form_data(q: 'ruby', lang: 'en')
req.body # => "q=ruby&lang=en"
req['Content-Type'] # => "application/x-www-form-urlencoded"
req.set_form_data([['q', 'ruby'], ['lang', 'en']])
req.body # => "q=ruby&lang=en"
req.set_form_data(q: ['ruby', 'perl'], lang: 'en')
req.body # => "q=ruby&q=perl&lang=en"
req.set_form_data([['q', 'ruby'], ['q', 'perl'], ['lang', 'en']])
req.body # => "q=ruby&q=perl&lang=en"
With string argument sep also given, uses that string as the separator:
req.set_form_data({q: 'ruby', lang: 'en'}, '|')
req.body # => "q=ruby|lang=en"
Gem::Net::HTTPHeader#form_data= is an alias for Gem::Net::HTTPHeader#set_form_data.
812 813 814 815 816 817 |
# File 'lib/rubygems/net-http/lib/net/http/header.rb', line 812 def set_form_data(params, sep = '&') query = URI.encode_www_form(params) query.gsub!(/&/, sep) if sep != '&' self.body = query self.content_type = 'application/x-www-form-urlencoded' end |