HTTPOISON - 在elixir中插入body参数

din*_*ina 9 http elixir

我正在尝试做一个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
Run Code Online (Sandbox Code Playgroud)

这对我很有用.

我的问题是 - 如何在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
Run Code Online (Sandbox Code Playgroud)

当我跑它时,我得到了

%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:...
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Dog*_*ert 22

你真的应该使用像毒药这样的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, [])
Run Code Online (Sandbox Code Playgroud)


Gaz*_*ler 5

您需要插值

body = '{
          "call": "MyCall",
          "app_key": "#{key}",
          "param": [
              {
                  "page"          : #{page},
                  "registres"     : "#{registres}",
                  "filter"        : "#{filter}"
              }
          ]
         }'
Run Code Online (Sandbox Code Playgroud)

如果您使用JSON库(通常选择毒药),则可以执行以下操作将Elixir数据结构转换为JSON表示形式:

body = %{
          call: "MyCall",
          app_key: key,
          param: [
              {
                  page: page,
                  registres: registers,
                  filter: filter
              }
          ]
         } |> Poison.encode!()
Run Code Online (Sandbox Code Playgroud)