简体   繁体   中英

Ruby Net::HTTP::Post overrides custom Content-Type header

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM