【问题标题】:How to add "Content-type" header in HTTP POST如何在 HTTP POST 中添加“Content-type”标头
【发布时间】:2016-01-30 05:12:35
【问题描述】:

我一直收到一个

400 "Bad Request" (Net::HTTPServerException) 

每当我尝试从各种方法添加内容类型标头时都会出错。

我见过几个不同的例子,但我都无法工作。我的目标是在我的请求中添加 JSON 的内容类型。没有标头,我的请求不会出错:

def post_data(notice)
    uri = URI('my uri is here')
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}")
    text = notice
    req.add_field('Content-Type', 'application/json')
    req.body = "{\"sensu_payload\" = #{payload(text).to_json}}"
    response = http.request(req)
    verify_response(response)
  end

我也试过这种添加标题的方法:

request = Net::HTTP::Post.new(@path, initheader = {'Content-Type' =>'application/json'})

【问题讨论】:

    标签: ruby json header content-type


    【解决方案1】:

    使用uri.path 代替@path

    request = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
    

    【讨论】:

    • 使用URIURI.parse 没有区别。他们都返回相同的东西。
    【解决方案2】:

    我认为你应该使用哈希[] 形式,而不是add_field

    req['Content-Type'] = 'application/json'
    

    请参阅文档中的“Setting Headers”示例和[]=

    另外,使用:

    "#{uri.path}?#{uri.query}"
    

    从来都不是一个好主意。字符串连接无法管理在查询中正确编码非法值的复杂性,这可能会破坏请求。考虑做这样的事情:

    require 'uri'
    
    require 'uri'
    
    foo = URI('http://www.example.com') # => #<URI::HTTP http://www.example.com>
    foo.query = URI::encode_www_form({'bar' => 'path/to/file', 'baz' => 'this & that'})
    foo.to_s # => "http://www.example.com?bar=path%2Fto%2Ffile&baz=this+%26+that"
    

    除此之外,我建议使用任何其他可用的 HTTP 客户端 gem。它们比 Net::HTTP 更容易处理意外情况,例如重定向和重试。它更像是构建其他方式无法提供的功能的基石。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-12
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 2014-05-23
      • 1970-01-01
      相关资源
      最近更新 更多