Skip to content

Commit

Permalink
googleapis#369 - Form encode paramaters when method == post/put and n…
Browse files Browse the repository at this point in the history
…o other body present
  • Loading branch information
sqrrrl committed Feb 25, 2016
1 parent 09ef486 commit 2c1fd12
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/google/apis/core/http_command.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,15 @@ def prepare!
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
Expand Down Expand Up @@ -263,9 +272,11 @@ def execute_once(client)
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)
Expand Down Expand Up @@ -296,6 +307,10 @@ def apply_request_options(req)

private

def form_encoded?
@form_encoded
end

def normalize_query_value(v)
case v
when Array
Expand Down
13 changes: 13 additions & 0 deletions spec/google/apis/core/http_command_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -281,4 +281,17 @@
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

0 comments on commit 2c1fd12

Please sign in to comment.