Skip to content

Commit 091bd6a

Browse files
authored
Merge pull request #828 from jnunemaker/issue-826
set Content-Type for Hash body in requests
2 parents 5c8b45e + 59c0ac5 commit 091bd6a

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/httparty/request.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,8 @@ def setup_raw_request
245245
if body.multipart?
246246
content_type = "multipart/form-data; boundary=#{body.boundary}"
247247
@raw_request['Content-Type'] = content_type
248+
elsif options[:body].respond_to?(:to_hash) && !@raw_request['Content-Type']
249+
@raw_request['Content-Type'] = 'application/x-www-form-urlencoded'
248250
end
249251
@raw_request.body = body.call
250252
end

spec/httparty/request_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,29 @@
378378
end
379379
end
380380
end
381+
382+
context "when body is a Hash" do
383+
subject(:headers) do
384+
@request.send(:setup_raw_request)
385+
headers = @request.instance_variable_get(:@raw_request).each_header.to_a
386+
Hash[*headers.flatten]
387+
end
388+
389+
it "sets header Content-Type: application/x-www-form-urlencoded" do
390+
@request.options[:body] = { foo: 'bar' }
391+
392+
expect(headers['content-type']).to eq('application/x-www-form-urlencoded')
393+
end
394+
395+
context "and header Content-Type is provided" do
396+
it "does not overwrite the provided Content-Type" do
397+
@request.options[:body] = { foo: 'bar' }
398+
@request.options[:headers] = { 'Content-Type' => 'application/json' }
399+
400+
expect(headers['content-type']).to eq('application/json')
401+
end
402+
end
403+
end
381404
end
382405

383406
describe 'http' do

0 commit comments

Comments
 (0)