How to use x-www-form-urlencoded in rails
If you're working with a Net::HTTP
object and therefore can't use the post_form
class method, encode the form values yourself, and provide the encoded value as the data string.
def post_form(path, form_params)
encoded_form = URI.encode_www_form(form_params)
headers = { content_type: "application/x-www-form-urlencoded" }
http_client.request_post(path, encoded_form, headers)
end
def http_client
http_client = Net::HTTP.new(@host, @port)
http_client.read_timeout = @read_timeout
http_client.use_ssl = true
http_client
end
This is what Net::HTTP.post_form
does internally.
To put it in simple terms, if you need to POST a application/www-url-form-encoded request:
# prepare the data:
params = [ [ "param1", "value1" ], [ "param2", "value2" ], [ "param3", "value3" ] ]
uri = ( "your_url_goes_here" )
# make your request:
response = Net::HTTP.post_form( uri, params )
if( response.is_a?( Net::HTTPSuccess ) )
# your request was successful
puts "The Response -> #{response.body}"
else
# your request failed
puts "Didn't succeed :("
end
Request bodies are defined by a form’s markup. In the form tag there is an attribute called
enctype
, this attribute tells the browser how to encode the form data. There are several different values this attribute can have. The default is application/x-www-form-urlencoded, which tells the browser to encode all of the values.
so when we want to send data to submit the form by those data as a params of the form the header will send application/x-www-form-urlencoded
for define enctype
http.set_form_data(param_hash)
For your
params = {
:code => "#{code}",
:redirect_uri => '/auth/exact/callback',
:grant_type => "authorization_code",
:client_id => "{CLIENT_ID}",
:client_secret => "CLIENT_SECRET"
}
uri = URI('https://start.exactonline.nl/api/oauth2/token')
#
Net::HTTP::Get.new(uri.request_uri).set_form_data(params)
or for post request of form submission use Net::HTTP::Post
and encode_www_form
is:
It Generate URL-encoded form data from given enum.
URI.encode_www_form([["name", "ruby"], ["language", "en"]])
#=> "name=ruby&language=en"
in your case
uri.query = URI.encode_www_form(params)
#=> "code=aas22&redirect_uri=...."
More info Here