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

问题描述 投票:7回答:3

我试图从ExactOnlineAPI访问令牌,但文档建议只使用x-www-form-urlencoded。 Ruby on Rails是否有这种编码,如果是这样,我该如何使用它。

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
ruby-on-rails ruby exact-online
3个回答
10
投票

请求主体由表单的标记定义。在表单标记中有一个名为enctype的属性,该属性告诉浏览器如何对表单数据进行编码。此属性可以具有多个不同的值。默认值为application / x-www-form-urlencoded,它告诉浏览器对所有值进行编码。

因此,当我们想要发送数据以通过这些数据提交表单作为表格的参数时,标题将发送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)

或者对于表单提交的发布请求使用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


4
投票

换句话说,如果您需要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

1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.