0

我正在尝试在 Elixir Phoenix 中使用 HTTPoison 转换 CURL 请求。当我运行 CURL 请求推荐时,它工作正常。当我尝试使用 HTTPoison 时出现“415 不支持的媒体类型”错误。

Phoenix/Elixir - cURL 有效,但 HTTPoison 失败

这是我的 CURL 请求

curl -u "user:password" -i -H "Accept:application/json" -X POST -d
 "amount=100&method=0&type=bank&receiver=CCC&info1=hello" 
 http://00.000.000.00:8080/services/id/999999111999/calculate

这是我的 Httpoison 请求

url = "myurl"
orderid = "myorderid"
headers = ["Accept", "application/json"]
request_body = '{"type" : "bank", 
         "method" : 0,
         "amount" : #{amount},
                 "receiver" : "CCC"
         "info1" : #{orderid}}'
dicoba = HTTPoison.post(url, headers, request_body, hackney: [basic_auth: {"#{user}", "#password"}]) |> IO.inspect
4

1 回答 1

1

curl 请求的内容类型为application/x-www-form-urlencoded,但是您的 HTTPoison 请求格式错误。您将 charlist 传递给请求正文,其中 HTTPoison 需要一个二进制文件,并且您没有指定请求的内容类型。

要创建application/x-www-form-urlencoded请求正文,您可以使用函数URI.encode_query/1.

url = "http://00.000.000.00:8080/services/id/999999111999/calculate"
payload = %{
  "amount" => 100,
  "method" => 0,
  "type" => "bank",
  "receiver" => "CCC",
  "info1" => "hello"
}
request_body = URI.encode_query(payload)
headers = [
  {"Accept", "application/json"}, 
  {"Content-Type", "application/x-www-form-urlencoded; charset=utf-8"}
]
dicoba = HTTPoison.post(url, request_body, headers, hackney: [basic_auth: {"#{user}", "#password"}])
于 2019-05-06T05:42:53.173 回答