简体   繁体   中英

Unable to make HTTP Post request using elixir?

The code i am trying with is:-

response = HTTPotion.post(url, [body: "{channel: \"#bot\", username: \"watson\", text: \"test\"}"])

The response i am getting is:-

%HTTPotion.Response{body: "invalid_payload",......, status_code: 400}

You made a successful request, but the body was wrong. In JSON there should be quotes around the field names:

[body: "{\"channel\": \"#{bot}\", \"username\": \"watson\", \"text\": \"test\"}"]

Also the syntax for string interpolation is #{variable_name} for example:

iex(1)> bot = "mybot"
iex(2)> "#{bot}"

Manually encoding JSON is error prone so you probably want to use Poison .

iex(3)> Poison.encode!(%{bot: bot, username: "watson", text: "test"})
"{\"username\":\"watson\",\"text\":\"test\",\"bot\":\"mybot\"}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM