簡體   English   中英

如何在HTTP POST中添加“ Content-type”標頭

[英]How to add “Content-type” header in HTTP POST

我不斷得到

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'})

使用uri.path而不是@path

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

我認為您應該使用hash []形式代替add_field

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

請參閱文檔中的“ 設置標題 ”示例和[]=

另外,使用:

"#{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相比,它們使處理意外情況(如重定向和重試)更加容易。 它更像是其他功能無法提供的功能的構建塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM