我试图做一个http请求
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
这对我很有用。
我的问题是 - 如何在body请求中插入变量。 意思是:
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
当我跑它时,我得到了
%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:...
有什么建议吗?
答案 0 :(得分:20)
你真的应该使用像Poison这样的JSON编码器。
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, [])
答案 1 :(得分:5)
您需要interpolate值:
body = '{
"call": "MyCall",
"app_key": "#{key}",
"param": [
{
"page" : #{page},
"registres" : "#{registres}",
"filter" : "#{filter}"
}
]
}'
如果您使用JSON库(Poison是一个受欢迎的选择)那么您可以执行类似的操作将Elixir数据结构转换为JSON表示:
body = %{
call: "MyCall",
app_key: key,
param: [
{
page: page,
registres: registers,
filter: filter
}
]
} |> Poison.encode!()