ruby-on-railsrubyexact-online

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

Solution

  • 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