HTTParty headers 奇怪的行为

HTTParty headers strange behavior

上下文:

我正在使用 HTTParty 在接受 application/json

的 API 上执行 POST 请求

我的 body 是这样的(作为哈希)

{: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" } )

但是当仅将 headers 中的 => 符号更改为 : 符号时,这不起作用(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 消费者来说,了解 HTTPParty 不接受 headers 的符号 但只接受字符串 很重要。

有关详细信息,请参阅 Content-Type Does not send when I try to use a new Hash syntax on header

谢谢@anothermh

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

当您输入 { "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" }

HTTPParty does not work with symbolized keys.