HTTP客户端帖子,未编译可选的splat参数

时间:2018-06-17 05:43:31

标签: crystal-lang

我想使用

发送HTTP post请求
HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, *, form : Hash(String, String) | NamedTuple)

我尝试这样做

url = "https://api.authy.com/protected/json/phones/verification/start"
headers = HTTP::Headers{"X-Authy-API-Key" => api_key}

form = {
  via:          "sms",
  country_code: country_code,
  phone_number: phone_number,
  code_length:  6,
  locale:       "ru",
}.to_h

response = HTTP::Client.post(url, headers: headers, form: form)

不幸的是,我收到了编译错误

no argument named 'form'
Matches are:
 - HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, body : BodyType = nil) (trying this one)
 - HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, body : BodyType = nil, &block)
 - HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, *, form : String | IO)
 - HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, *, form : String | IO, &block)
 - HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, *, form : Hash(String, String) | NamedTuple)
 - HTTP::Client#post(path, headers : HTTP::Headers | ::Nil = nil, *, form : Hash(String, String) | NamedTuple, &block)

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

发生此编译错误是因为.to_hnamed tuple上返回Hash(Symbol, Int32 | String),并且与HTTP::Client.post的任何定义都不相符。

要解决此问题,我建议明确将form定义为Hash(String, String),并用字符串表示替换键和值:

form : Hash(String, String) = {
  "via"          => "sms",
  "country_code" => country_code.to_s, # assuming this is not a string
  "phone_number" => phone_number,
  "code_length"  => "6",
  "locale"       => "ru",
}