【问题标题】:HTTParty headers strange behaviorHTTParty 标头奇怪的行为
【发布时间】:2019-06-11 10:20:29
【问题描述】:

上下文:

我正在使用 HTTParty 在接受 application/json 的 API 上执行 POST 请求

我的身体是这样的(作为哈希)

{:contact_id =>"12345679", 
 :items=> [
      {:contact_id=>"123456789", :quantity=>"1", :price=>"0"},
      {:contact_id=>"112315475", :quantity=>"2", :price=>"2"}
]}

问题:

当我编写以下代码时,这是有效的:

HTTParty.post('https://some-url', body: content.to_json, headers: { "Content-Type" => "application/json" } )

但是当仅将标题中的=> 符号更改为: 符号时,这不起作用(API 响应某些参数丢失)

HTTParty.post('https://some-url', body: content.to_json, headers: { "Content-Type": "application/json" } )

问题:

为什么将"Content-Type" => "application/json" 更改为"Content-Type": "application/json" 会导致错误?

我认为这是我不理解的 Ruby 哈希。

编辑:

我认为我的问题与Why is this string key in a hash converted to a symbol?不重复

对于 HTTParty 消费者来说,了解 HTTParty 不接受标头的符号只接受字符串,这一点很重要。

有关详细信息,请参阅 Content-Type Does not send when I try to use a new Hash syntax on headerPassing headers and query params in HTTparty

谢谢@anothermh

【问题讨论】:

    标签: ruby httparty


    【解决方案1】:

    Ruby 中的哈希键可以是任何对象类型。例如,它们可以是字符串,也可以是符号。在哈希键中使用冒号 (:) 告诉 Ruby 您正在使用符号。使用字符串(或其他对象类型,如整数)作为密钥的唯一方法是使用哈希火箭 (=>)。

    当您输入{ "Content-Type": "application/json" } 时,Ruby 会将字符串"Content-Type" 转换为符号:"Content-Type"。您可以在控制台中自己查看:

    { "Content-Type": "application/json" }
    => { :"Content-Type" => "application/json" }
    

    当您使用哈希火箭时,它不会被转换并且仍然是一个字符串:

    { "Content-Type" => "application/json" }
    => { "Content-Type" => "application/json" }
    

    HTTP派对does not work with symbolized keys.

    【讨论】:

    • 所以 HTTParty 只接受字符串作为标题,如果我理解得很好
    • 正确。阅读更多 herehere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多