HTTPoison

HTTP client for Elixir, based on HTTPotion (documentation).
Note about broken ssl in Erlang 19
Until this issue is fixed ssl handshakes may fail. If you receive this error:
{:error, %HTTPoison.Error{id: nil, reason: :closed}}
Try the following fix:
HTTPoison.get("https://example.com/", [], [ ssl: [{:versions, [:'tlsv1.2']}] ])
But… why something so similar to HTTPotion?
HTTPoison uses hackney to execute HTTP requests instead of ibrowse. I like hackney :thumbsup:
Using hackney we work only with binaries instead of string lists.
Installation
First, add HTTPoison to your mix.exs
dependencies:
def deps do
[{:httpoison, "~> 1.4"}]
end
and run $ mix deps.get
. Add :httpoison
to your applications list if your Elixir version is 1.3 or lower:
def application do
[applications: [:httpoison]]
end
Usage
iex> HTTPoison.start
iex> HTTPoison.get! "http://httparrot.herokuapp.com/get"
%HTTPoison.Response{
body: "{\n \"args\": {},\n \"headers\": {} ...",
headers: [{"Connection", "keep-alive"}, {"Server", "Cowboy"},
{"Date", "Sat, 06 Jun 2015 03:52:13 GMT"}, {"Content-Length", "495"},
{"Content-Type", "application/json"}, {"Via", "1.1 vegur"}],
status_code: 200
}
iex> HTTPoison.get! "http://localhost:1"
** (HTTPoison.Error) :econnrefused
iex> HTTPoison.get "http://localhost:1"
{:error, %HTTPoison.Error{id: nil, reason: :econnrefused}}
iex> HTTPoison.post "http://httparrot.herokuapp.com/post", "{\"body\": \"test\"}", [{"Content-Type", "application/json"}]
{:ok, %HTTPoison.Response{body: "{\n \"args\": {},\n \"headers\": {\n \"host\": \"httparrot.herokuapp.com\",\n \"connection\": \"close\",\n \"accept\": \"application/json\",\n \"content-type\": \"application/json\",\n \"user-agent\": \"hackney/1.6.1\",\n \"x-request-id\": \"4b85de44-6227-4480-b506-e3b9b4f0318a\",\n \"x-forwarded-for\": \"76.174.231.199\",\n \"x-forwarded-proto\": \"http\",\n \"x-forwarded-port\": \"80\",\n \"via\": \"1.1 vegur\",\n \"connect-time\": \"1\",\n \"x-request-start\": \"1475945832992\",\n \"total-route-time\": \"0\",\n \"content-length\": \"16\"\n },\n \"url\": \"http://httparrot.herokuapp.com/post\",\n \"origin\": \"10.180.37.142\",\n \"form\": {},\n \"data\": \"{\\\"body\\\": \\\"test\\\"}\",\n \"json\": {\n \"body\": \"test\"\n }\n}",
headers: [{"Connection", "keep-alive"}, {"Server", "Cowboy"},
{"Date", "Sat, 08 Oct 2016 16:57:12 GMT"}, {"Content-Length", "681"},
{"Content-Type", "application/json"}, {"Via", "1.1 vegur"}],
status_code: 200}}
You can also easily pattern match on the HTTPoison.Response
struct:
case HTTPoison.get(url) do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
IO.puts body
{:ok, %HTTPoison.Response{status_code: 404}} ->
IO.puts "Not found :("
{:error, %HTTPoison.Error{reason: reason}} ->
IO.inspect reason
end
Comments
0 comments
Please sign in to leave a comment.