如何在Elixir Phoenix中将CURL请求转换为Httpoison请求

时间:2019-05-06 04:13:13

标签: curl elixir phoenix httpoison

我正在Elixir Phoenix中尝试使用HTTPoison转换CURL请求。 当我运行CURL请求命令时,它工作正常。尝试使用HTTPoison时出现“ 415 Unsupported media type”错误。

Phoenix/Elixir - cURL works, but HTTPoison fails

这是我的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

1 个答案:

答案 0 :(得分:0)

curl请求的内容类型为 application / x-www-form-urlencoded ,但是您的HTTPoison请求格式错误。您将一个字符列表传递给了请求正文,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, headers, request_body, hackney: [basic_auth: {"#{user}", "#password"}])