我想使用
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)
正确的方法是什么?
发生此编译错误是因为.to_h
在命名元组上返回一个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",
}