简体   繁体   English

Ruby Net :: HTTP :: Post覆盖自定义Content-Type标头

[英]Ruby Net::HTTP::Post overrides custom Content-Type header

It seems that Ruby's Net::HTTP::Post overrides the custom Content-Type header. 似乎Ruby的Net::HTTP::Post覆盖了自定义Content-Type标头。 When I set the header 'Content-Type':'application/json' I receive the following error from the server: 当我设置标题'Content-Type':'application/json'我从服务器收到以下错误:

HTTP Status 400 - Bad Content-Type header value: 'application/json, application/x-www-form-urlencoded'

Notice application/x-www-form-urlencoded . 注意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: 有趣的是,以下代码使用Net::HTTP以不同的方式工作:

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 : 原因是在您显式设置request.form_data的第一个代码段中:

req.form_data = params

Forms are encoded with x-www-urlencoded implicitly . 表单使用x-www-urlencoded隐式x-www-urlencoded

Probably you'd better to set body or set in explicitly in Net::HTTP::Post.new . 可能最好在Net::HTTP::Post.new设置body或显式设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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