Reputation: 25102
It seems that Ruby's Net::HTTP::Post
overrides the custom Content-Type header. When I set the header 'Content-Type':'application/json'
I receive the following error from the server:
HTTP Status 400 - Bad Content-Type header value: 'application/json, application/x-www-form-urlencoded'
Notice application/x-www-form-urlencoded
. Why is it there? Is there a way to remove it?
My code:
def post(uri, params)
req = Net::HTTP::Post.new(uri.path, 'Content-Type':'application/json')
req.form_data = params
Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
end
Interestingly the following code which takes a different approach using Net::HTTP
works:
def post(uri, params)
headers = {'Content-Type' =>'application/json'}
request = Net::HTTP.new(uri.host, uri.port)
request.post(uri.path, params.to_json, headers)
end
Upvotes: 0
Views: 854
Reputation: 121000
The reason is in the first snippet you explicitly set request.form_data
:
req.form_data = params
Forms are encoded with x-www-urlencoded
implicitly.
Probably you’d better to set body
or set in explicitly in Net::HTTP::Post.new
.
Upvotes: 2