Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use x-www-form-urlencoded in rails

Am trying to access the token from ExactOnlineAPI but the documentation recommends to only use x-www-form-urlencoded. Does Ruby on Rails has this kind of encoding, if so how can i use it.

What is the different between x-www-form-urlencoded and encode_www_form

 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')
#
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
puts "Access Token: "+res.body
like image 290
Little Phild Avatar asked Dec 10 '15 14:12

Little Phild


People also ask

Why do we use X-www-form-Urlencoded?

Hence, it is advised to use x-www-form-urlencoded when you have to send form data e.g. most of the web form which asks you to enter values and use multipart/form-data when you have to upload files to the server as used here.

What is X-www-form-Urlencoded?

The application/x-www-form-urlencoded content type describes form data that is sent in a single block in the HTTP message body. Unlike the query part of the URL in a GET request, the length of the data is unrestricted.

How do you send application X-www-form-Urlencoded in Postman?

If your API requires url-encoded data, select x-www-form-urlencoded in the Body tab of your request. Enter your key-value pairs to send with the request and Postman will encode them before sending.


1 Answers

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

like image 145
Rajarshi Das Avatar answered Oct 22 '22 06:10

Rajarshi Das