I'm trying to do a http request
def getPage() do
url = "http://myurl"
body = '{
"call": "MyCall",
"app_key": "3347249693",
"param": [
{
"page" : 1,
"registres" : 100,
"filter" : "N"
}
]
}'
headers = [{"Content-type", "application/json"}]
HTTPoison.post(url, body, headers, [])
end
this works for me well.
my question is - how can I insert variables in the body request. meaning:
def getPage(key, page, registers, filter) do
url = "http://myurl"
body = '{
"call": "MyCall",
"app_key": key,
"param": [
{
"page" : page,
"registres" : registers,
"filter" : filter
}
]
}'
headers = [{"Content-type", "application/json"}]
HTTPoison.post(url, body, headers, [])
end
when I run it I get
%HTTPoison.Response{body: "\nFatal error: Uncaught exception 'Exception' with message 'Invalid JSON object' in /myurl/www/myurl_app/api/lib/php-wsdl/class.phpwsdl.servers.php:...
any suggestions?
You really should be using a JSON encoder like Poison for this.
url = "http://myurl"
body = Poison.encode!(%{
"call": "MyCall",
"app_key": key,
"param": [
%{
"page": page,
"registres": registers,
"filter": filter
}
]
})
headers = [{"Content-type", "application/json"}]
HTTPoison.post(url, body, headers, [])
You need to interpolate the values:
body = '{
"call": "MyCall",
"app_key": "#{key}",
"param": [
{
"page" : #{page},
"registres" : "#{registres}",
"filter" : "#{filter}"
}
]
}'
If you use a JSON library (Poison is a popular choice) Then you could do something like this to turn Elixir data structures into a JSON representation:
body = %{
call: "MyCall",
app_key: key,
param: [
{
page: page,
registres: registers,
filter: filter
}
]
} |> Poison.encode!()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With