使用Elixir HTTPoison Library创建Github令牌

王志軍*_*王志軍 6 elixir

我想使用HTTPoison库在Elixir中创建一个Github令牌,但我不知道如何发送HTTPoison参数.

使用时curl,它会是这样的

$ curl -i -u "ColdFreak" -H "X-GitHub-OTP: 123456" -d '{"scopes": ["repo", "user"], "note"
: "getting-started"}' https://api.github.com/authorizations
Run Code Online (Sandbox Code Playgroud)

当我使用HTTPoison库时,我无法弄清楚如何发布它.

url = "https://api.github.com/authorizations"
HTTPoison.post!(url, [scopes: ["repo", "user"], note: "getting-started"],  %{"X-GitHub-OTP" => "12345"})
Run Code Online (Sandbox Code Playgroud)

然后它给出了类似的错误

** (ArgumentError) argument error
            :erlang.iolist_to_binary([{"scopes", ["repo", "user"]}, {"note", "getting-started"}])
  (hackney) src/hackney_client/hackney_request.erl:338: :hackney_request.handle_body/4
  (hackney) src/hackney_client/hackney_request.erl:79: :hackney_request.perform/2
Run Code Online (Sandbox Code Playgroud)

有人能告诉我如何以正确的方式做到这一点

HTTPoison的文档在这里

Gaz*_*ler 11

问题在于您的身体HTTPoison需要格式为二进制或元组{:form, [foo: "bar"]}:

HTTPoison.post!(url, {:form, [scopes: "repo, user", note: "getting-started"]},  %{"X-GitHub-OTP" => "610554"})
Run Code Online (Sandbox Code Playgroud)

要么

HTTPoison.post!(url, "{\"scopes\": \"repo, user\", \"note\": \"getting-started\"}",  %{"X-GitHub-OTP" => "610554"})
Run Code Online (Sandbox Code Playgroud)

您可以使用Poison库生成上面的JSON:

json = %{scopes: "repo, user", note: "getting-started"} |> Poison.encode!
HTTPoison.post!(url, json, %{"X-GitHub-OTP" => "610554"})
Run Code Online (Sandbox Code Playgroud)