diff --git a/lib/google/apis/core/http_command.rb b/lib/google/apis/core/http_command.rb index d18eb85f2..b83693884 100644 --- a/lib/google/apis/core/http_command.rb +++ b/lib/google/apis/core/http_command.rb @@ -145,6 +145,15 @@ module Google header.update(options.header) if options && options.header self.url = url.expand(params) if url.is_a?(Addressable::Template) url.query_values = query.merge(url.query_values || {}) + + if [:post, :put].include?(method) && body.nil? + @form_encoded = true + self.body = Addressable::URI.form_encode(url.query_values(Array)) + self.header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8' + self.url.query_values = {} + else + @form_encoded = false + end end # Release any resources used by this command @@ -263,9 +272,11 @@ module Google response = client.send(method, url, body) do |req| # Temporary workaround for Hurley bug where the connection preference # is ignored and it uses nested anyway - req.url.query_class = Hurley::Query::Flat - query.each do | k, v| - req.url.query[k] = normalize_query_value(v) + unless form_encoded? + req.url.query_class = Hurley::Query::Flat + query.each do | k, v| + req.url.query[k] = normalize_query_value(v) + end end # End workaround apply_request_options(req) @@ -296,6 +307,10 @@ module Google private + def form_encoded? + @form_encoded + end + def normalize_query_value(v) case v when Array diff --git a/spec/google/apis/core/http_command_spec.rb b/spec/google/apis/core/http_command_spec.rb index b3695b26b..d9c98df66 100644 --- a/spec/google/apis/core/http_command_spec.rb +++ b/spec/google/apis/core/http_command_spec.rb @@ -281,4 +281,17 @@ RSpec.describe Google::Apis::Core::HttpCommand do command.query['b'] = false command.execute(client) end + + it 'should form encode parameters when method is POST and no body present' do + stub_request(:post, 'https://www.googleapis.com/zoo/animals') + .with(body: 'a=1&a=2&a=3&b=hello&c=&d=0') + .to_return(status: [200, '']) + command = Google::Apis::Core::HttpCommand.new(:post, 'https://www.googleapis.com/zoo/animals') + command.query['a'] = [1,2,3] + command.query['b'] = 'hello' + command.query['c'] = nil + command.query['d'] = 0 + command.execute(client) + end + end