1

I'm trying to transform CURL request with HTTPoison in Elixir Phoenix. When I run CURL request commend, It work fine.I got "415 Unsupported media type" error when I try with HTTPoison.

Phoenix/Elixir - cURL works, but HTTPoison fails

Here is my CURL request

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

Here is my Httpoison request

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
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
Thatoe Aung
  • 167
  • 4
  • 12

1 Answers1

2

The curl request is in the content type application/x-www-form-urlencoded, but your HTTPoison request is, well, malformed. You passed a charlist to the request body, where HTTPoison expects a binary, and you didn't specify the request's content type.

To create a application/x-www-form-urlencoded request body, you can use the function 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"}])
Aetherus
  • 8,720
  • 1
  • 22
  • 36