ruby-on-rails – 如何在rails中使用x-www-form-urlencoded

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何在rails中使用x-www-form-urlencoded前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从 ExactOnlineAPI访问令牌,但文档建议只使用x-www-form-urlencoded. Ruby on Rails是否有这种编码,如果是这样,我该如何使用它.

x-www-form-urlencoded和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

解决方法

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.

因此,当我们想要发送数据以通过这些数据提交表格作为表格的参数时,标题将发送application / x-www-form-urlencoded用于定义enctype

http.set_form_data(param_hash)

为您

params =  {
         :code => "#{code}",:client_secret => "CLIENT_SECRET"
       }
  uri = URI('https://start.exactonline.nl/api/oauth2/token')
  #

  Net::HTTP::Get.new(uri.request_uri).set_form_data(params)

或者对于表单提交的发布请求使用Net :: HTTP :: Post

和encode_www_form是:

它从给定的枚举生成URL编码的表单数据.

URI.encode_www_form([["name","ruby"],["language","en"]])
#=> "name=ruby&language=en"

在你的情况下

uri.query = URI.encode_www_form(params)
#=> "code=aas22&redirect_uri=...."

更多信息Here

猜你在找的Ruby相关文章