3 HTTP Client

3.1 Configuration

The HTTP client default profile is started when the Inets application is started and is then available to all processes on that Erlang node. Other profiles can also be started at application startup, or profiles can be started and stopped dynamically in runtime. Each client profile spawns a new process to handle each request, unless a persistent connection can be used with or without pipelining. The client adds a host header and an empty te header if there are no such headers present in the request.

The client supports IPv6 as long as the underlying mechanisms also do so.

The following is to be put in the Erlang node application configuration file to start a profile at application startup:

[{inets, [{services, [{httpc, PropertyList}]}]}]

For valid properties, see httpc(3).

3.2 Getting Started

Start Inets:

1 > inets:start().
     ok

The following calls use the default client profile. Use the proxy "www-proxy.mycompany.com:8000", except from requests to localhost. This applies to all the following requests.

Example:

2 > httpc:set_options([{proxy, {{"www-proxy.mycompany.com", 8000},
["localhost"]}}]).
ok

The following is an ordinary synchronous request:

3 > {ok, {{Version, 200, ReasonPhrase}, Headers, Body}} =
httpc:request(get, {"http://www.erlang.org", []}, [], []).

With all the default values presented, a get request can also be written as follows:

4 > {ok, {{Version, 200, ReasonPhrase}, Headers, Body}} =
httpc:request("http://www.erlang.org").

The following is an ordinary asynchronous request:

5 > {ok, RequestId} =
httpc:request(get, {"http://www.erlang.org", []}, [], [{sync, false}]).

The result is sent to the calling process as {http, {ReqestId, Result}}.

In this case, the calling process is the shell, so the following result is received:

6 > receive {http, {RequestId, Result}} -> ok after 500 -> error end.
ok

This sends a request with a specified connection header:

7 > {ok, {{NewVersion, 200, NewReasonPhrase}, NewHeaders, NewBody}} =
httpc:request(get, {"http://www.erlang.org", [{"connection", "close"}]},
[], []).

This sends an HTTP request over a unix domain socket (experimental):

8 > httpc:set_options([{ipfamily, local},
{unix_socket,"/tmp/unix_socket/consul_http.sock"}]).
9 > {ok, {{NewVersion, 200, NewReasonPhrase}, NewHeaders, NewBody}} =
httpc:request(put, {"http:///v1/kv/foo", [], [], "hello"}, [], []).

Start an HTTP client profile:

10 > {ok, Pid} = inets:start(httpc, [{profile, foo}]).
{ok, <0.45.0>}       

The new profile has no proxy settings, so the connection is refused:

11 > httpc:request("http://www.erlang.org", foo).
{error, econnrefused}

Stop the HTTP client profile:

12 > inets:stop(httpc, foo).
ok

Alternative way to stop the HTTP client profile:

13 > inets:stop(httpc, Pid).
ok

© 2010–2021 Ericsson AB
Licensed under the Apache License, Version 2.0.