HTTP clients

An HTTP client is a program that writes a request on a socket and reads the answer back. Erlang ships one: httpc, in the inets application. It handles the request line, the headers, the content length, chunked responses and the connection pool, so a program that calls it deals with a tuple instead of a stream of bytes. This lesson builds the smallest server that speaks HTTP to have something to call, then uses the client against it, which keeps the example inside the machine.

A local server

The server below is the same gen_tcp of the sockets lesson with an HTTP answer: it accepts one connection, reads the request line, and writes a status line, two headers, a content length and the body. The program plays the client with a raw socket, which shows exactly what travels:

micro_http.erl

-module(micro_http). -export([main/0]). main() -> {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}, {reuseaddr, true}]), {ok, Port} = inet:port(Listen), spawn_link(fun() -> serve(Listen) end), {ok, Client} = gen_tcp:connect({127, 0, 0, 1}, Port, [binary, {active, false}]), Request = <<"GET /hello HTTP/1.1\r\nHost: localhost\r\n\r\n">>, ok = gen_tcp:send(Client, Request), {ok, Response} = gen_tcp:recv(Client, 0, 2000), [StatusLine | Rest] = binary:split(Response, <<"\r\n">>, [global]), io:format("status: ~p~n", [StatusLine]), io:format("body: ~p~n", [lists:last(Rest)]), ok = gen_tcp:close(Client), ok = gen_tcp:close(Listen). serve(Listen) -> {ok, Socket} = gen_tcp:accept(Listen, 2000), {ok, _Request} = gen_tcp:recv(Socket, 0, 2000), Body = <<"hello from the local server">>, Length = integer_to_binary(byte_size(Body)), Response = [<<"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n">>, <<"Content-Length: ">>, Length, <<"\r\nConnection: close\r\n\r\n">>, Body], ok = gen_tcp:send(Socket, Response), ok = gen_tcp:close(Socket).

erlc micro_http.erl

erl -noshell -eval 'micro_http:main(), halt().'

status: <<"HTTP/1.1 200 OK">> body: <<"hello from the local server">>

The whole HTTP response is in the first read, because the message is small and the connection closes after it. That is the one thing this server does not do like a real one: a server keeps the connection open and frames the body with the length it announced, which is the part httpc takes care of for a client.

httpc

Nothing in inets runs until the application is started, so the first call of a program is application:ensure_all_started(inets). After that, httpc:request/1 takes a URL and answers the whole exchange in one tuple. The program below is an escript, a whole program in one file, and it starts a fixture server of its own so that no website and no network are involved:

http_client.escript

#!/usr/bin/env escript %%! -noshell main(_Args) -> {ok, _} = application:ensure_all_started(inets), {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}, {reuseaddr, true}]), {ok, Port} = inet:port(Listen), spawn_link(fun() -> serve(Listen, 3) end), Url = "http://127.0.0.1:" ++ integer_to_list(Port), {ok, {{_, Status, _}, Headers, Body}} = httpc:request(Url ++ "/hello"), io:format("status: ~p~n", [Status]), io:format("type: ~p~n", [proplists:get_value("content-type", Headers)]), io:format("body: ~p~n", [Body]), {ok, {{_, Same, _}, _Headers2, Binary}} = httpc:request(get, {Url ++ "/hello", []}, [], [{body_format, binary}]), io:format("binary body: ~p~n", [Binary]), io:format("same status: ~p~n", [Same =:= Status]), io:format("slow request: ~p~n", [httpc:request(get, {Url ++ "/slow", []}, [{timeout, 50}], [])]), io:format("closed port: ~p~n", [httpc:request("http://127.0.0.1:1/")]). serve(Listen, Count) when Count > 0 -> {ok, Socket} = gen_tcp:accept(Listen, 5000), {ok, RequestLine} = gen_tcp:recv(Socket, 0, 5000), maybe_delay(RequestLine), Body = <<"hello from the local server">>, Length = integer_to_binary(byte_size(Body)), Response = [<<"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n">>, <<"Content-Length: ">>, Length, <<"\r\nConnection: close\r\n\r\n">>, Body], ok = gen_tcp:send(Socket, Response), ok = gen_tcp:close(Socket), serve(Listen, Count - 1); serve(_Listen, 0) -> ok. maybe_delay(RequestLine) -> case binary:match(RequestLine, <<"/slow">>) of nomatch -> ok; _ -> timer:sleep(200) end.

escript http_client.escript

status: 200 type: "text/plain" body: "hello from the local server" binary body: <<"hello from the local server">> same status: true slow request: {error,timeout} closed port: {error,{failed_connect,[{to_address,{"127.0.0.1",1}}, {inet,[inet],econnrefused}]}}

Six answers, one per question a client has. The status is a number and the reason phrase is thrown away. The header list is a proplist of string pairs, so proplists:get_value/2 reads one. The body is a string by default and a binary when it was asked for, and the two requests report the same status because the method and the URL were the same.

The answer

The response tuple has three levels: the outer ok says the exchange happened, the triple holds the version, the status code and the reason phrase, and the last element is the body. A status of 404 or 500 is not an error tuple: the request worked and the server answered, so the answer stays {ok, ...} and the code tells you how it went. The error tuple is for the exchange itself, as the last two lines of the run show: a server that never answers within the timeout, and a port where nothing listens.

The body_format option is a request option, not an HTTP option, which is why it travels in the fourth argument of httpc:request/4. Ask for a binary whenever the body is not text: an image or a compressed file as a string is a list of integers, and every operation on it is slower and easy to get wrong.

Options and timeout

The third argument of httpc:request/4 holds the HTTP options and the fourth the request options. The timeout is an HTTP option and counts milliseconds for the whole exchange; without it the client waits for as long as the server keeps the socket open, which is the wrong default for a program with a user in front of it. A redirect follows the autoredirect option, and a proxy is one more entry in the same list.

For many requests to one host, let httpc keep its pool: the default profile handles several connections per host, and httpc:set_options/1 raises max_sessions and max_keep_alive_length. Build one profile per host when the proxy or the certificates differ. For HTTP/2, a stream per request, or a connection that must be tuned in ways the standard library does not expose, the ecosystem uses other clients; those come from outside OTP, and this course stays on the standard library, so the lesson names them and does not run them.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which application provides the httpc client?

    Answer

    inets

    httpc ships with inets, so the application must be started before the first request.

  2. Which call starts inets and its dependencies?

    Answer

    application:ensure_all_started(inets)

    The call starts inets and every application it needs, and answers {ok, Started}.

  3. What is the shape of a successful httpc:request/1 answer?

    Answer

    {ok, {{Version, Status, Reason}, Headers, Body}}

    The status line is a triple inside the response tuple, and the response sits inside ok.

  4. What is the type of the body by default?

    Answer

    A string, that is a list of characters

    httpc answers a string unless {body_format, binary} is requested.

  5. Which argument of httpc:request/4 holds the timeout?

    Answer

    The HTTP options list

    The timeout is an HTTP option, so it goes in the third argument.

  6. What does this program print? -module(q3). -export([main/0]). main() -> {ok, _} = application:ensure_all_started(inets), {ok, Listen} = gen_tcp:listen(0, [binary, {active, false}]), {ok, Port} = inet:port(Listen), Url = "http://127.0.0.1:" ++ integer_to_list(Port) ++ "/", R = httpc:request(get, {Url, []}, [{timeout, 50}], []), ok = gen_tcp:close(Listen), io:format("~p~n", [R]).

    Answer

    {error,timeout}

    The socket accepts the connection and never answers, so the client gives up after the fifty milliseconds it was given.

  7. What does this program print when nothing listens on the port? -module(q1). -export([main/0]). main() -> {ok, _} = application:ensure_all_started(inets), R = httpc:request("http://127.0.0.1:1/"), io:format("~p~n", [element(1, R)]).

    Answer

    error

    The exchange itself failed, so the answer is an error tuple and its first element is the atom error.

  8. What does this program print? -module(q2). -export([main/0]). main() -> Headers = [{"content-type", "text/plain"}, {"content-length", "5"}], io:format("~p~n", [proplists:get_value("content-type", Headers)]).

    Answer

    "text/plain"

    The headers are a proplist, and get_value answers the value of the first pair with that key.

  9. What does this program print? -module(q4). -export([main/0]). main() -> {ok, _} = application:ensure_all_started(inets), {ok, Listen} = gen_tcp:listen(0, [binary, {packet, line}, {active, false}]), {ok, Port} = inet:port(Listen), spawn_link(fun() -> serve(Listen) end), Url = "http://127.0.0.1:" ++ integer_to_list(Port) ++ "/", {ok, {{_, Status, _}, _Headers, Body}} = httpc:request(Url), io:format("~p~n", [{Status, Body}]). serve(Listen) -> {ok, Socket} = gen_tcp:accept(Listen, 5000), {ok, _Line} = gen_tcp:recv(Socket, 0, 5000), Body = <<"done">>, Response = [<<"HTTP/1.1 201 Created\r\nContent-Length: 4\r\n">>, <<"Connection: close\r\n\r\n">>, Body], ok = gen_tcp:send(Socket, Response), ok = gen_tcp:close(Socket).

    Answer

    {201,"done"}

    The status line carries 201, and the body comes back as a string because no binary format was asked for.

  10. How do you read one header value?

    Answer

    proplists:get_value/2 on the headers

    The headers are a proplist of string pairs, and proplists:get_value picks one value.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev