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

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

我正在尝试从 ExactOnlineAPI 访问令牌,但文档建议仅使用 x-www-form-urlencoded。 Rails 上的 Ruby 是否有这种编码,如果有我该如何使用它。

x-www-form-urlencodedencode_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.

所以当我们想要发送数据以通过这些数据作为表单的参数提交表单时,header 将发送 application/x-www-form-urlencoded 以定义 enctype

http.set_form_data(param_hash)

为了你的

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)

或 post 表单提交请求使用 Net::HTTP::Post

encode_www_form是:

它根据给定的枚举生成 URL-encoded 表单数据。

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

你的情况

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

更多信息Here

简单来说,如果你需要POST一个application/www-url-form-encoded请求:

# 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

如果您使用的是 Net::HTTP 对象,因此无法使用 post_form class 方法,请自行对表单值进行编码,并提供编码值作为数据字符串。

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

这是what Net::HTTP.post_form does internally