【问题标题】:how to translate curl to elixir httpoison如何将 curl 翻译成 elixir httpoison
【发布时间】:2017-05-12 04:05:17
【问题描述】:

我有一个来自 api 的 curl 命令示例:

curl -sd '{"inputs":[{"addresses": ["add42af7dd58b27e1e6ca5c4fdc01214b52d382f"]}],"outputs":[{"addresses": ["884bae20ee442a1d53a1d44b1067af42f896e541"], "value": 4200000000000000}]}' https://api.blockcypher.com/v1/eth/main/txs/new?token=YOURTOKEN

我不知道如何将其转换为 Elixir 的 HTTPoison。我已经尝试了几个小时。我什至不能开始提及我经历过的所有迭代,但这就是我现在所处的位置:

Connect.post( "https://api.blockcypher.com/v1/eth/main/txs/new?token=#{@token}",
              "",
              [
                { "inputs",  "{addresses, #{address_from}}"},
                {  "outputs", "[{addresses, #{address_to}}, {value, #{eth_amount}}]"}
              ]
            )

与我在此之前尝试过的大多数事情不同,它实际上会到达他们的服务器并给出响应:

"{\"error\": \"Couldn't deserialize request: EOF\"}"
%{"error" => "Couldn't deserialize request: EOF"}
** (FunctionClauseError) no function clause matching in Base.encode16/2
         (elixir) lib/base.ex:175: Base.encode16(nil, [])
    (blockcypher) lib/blockcypher/handler.ex:55: Blockcypher.Handler.post_transa
ction_new/4
iex(46)>

你能帮帮我吗?我尝试将数据放在正文部分而不是标题中,但没有成功。

【问题讨论】:

    标签: rest curl elixir httpoison


    【解决方案1】:

    数据应该是HTTPoison.post/2 的第二个参数,并且应该被编码为 JSON。您的数据格式也有误。

    这应该可行:

    Connect.post(
      "https://api.blockcypher.com/v1/eth/main/txs/new?token=#{@token}",
      "",
      Poison.encode!(
        %{"inputs" => [%{"addresses" => [address_from]}],
          "outputs" => [%{"addresses" => [address_to],
                          "value" => eth_amount}]})
    )
    

    【讨论】:

    • 感谢 Dogbert,不幸的是这没有用。我收到一条错误消息,提示 ** (Poison.SyntaxError) Unexpected end of input at position 0 (poison) lib/poison/parser.ex:55: Poison.Parser.parse!/2 (poison) lib/poison.ex:83: Poison.decode!/2 (httpoison) lib/httpoison/base.ex:471: HTTPoison.Base.response/6 (blockcypher) lib/blockcypher/handler.ex:47: Blockcypher.Handler.post_transa ction_new/4
    • @Dogbert 在原始请求中,inputsoutputs[addresses+value] 都是数组。我相信将地图包装到[] 中应该可以正常工作。
    • @mudasobwa 谢谢!我已经用Poison.decode! 解码了原始字符串并复制粘贴了它。希望现在没有错误! @LegitStack 你能试试我的新代码吗?
    • 成功了!稍作修改,删除了第 3 行 "", 谢谢大家,你们是巫师!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多