sami alagi
sami alagi

Reputation: 31

add timeout with http:request

I developed this function :

sms_sentByHttp(NumPhone,MsgReceived) ->

    NumPhoneTroncated = string:sub_string(NumPhone,2),
    {X1, X2, X3} = erlang:now(),
    Rand = random:uniform(9999),
    {{Y,M,D},{H,Mn,S}}=erlang:universaltime(),
    Ws_req_id = lists:flatten(io_lib:format("~p~p~p~p~p~p~p~p", [X3, Rand,Y,M,D,H,M,S])),
   Url = io_lib:format("http://localhost:7703/enda?msg=~s&from=~s&id=~s", [http_urii:encode(MsgReceived),http_urii:encode(NumPhoneTroncated),Ws_req_id]),

    case http:request(lists:flatten(Url)) of
        {ok , A} -> io:format("response sent\n");
        {error, B} -> io:format("response not sent\n ~w\n", [B])
    end.

Now I want to add the notion of timeout in the request and after for example 20 seconds. I want to display error from server

I tried with :

case http:request(lists:flatten(Url),[ {timeout,timer:seconds(20)}]) of
           {ok , A} -> io:format("response sent\n");
    {error, B} -> io:format("error from server\n ~w\n", [B])
        end.

Upvotes: 3

Views: 1419

Answers (1)

Soup in Boots
Soup in Boots

Reputation: 2392

I'd recommend using ibrowse as your HTTP client. It includes a timeout parameter in send_req/6 (and options for more fine-tuned timeouts). It's also generally more efficient than the inets library included by default.

Another option is lhttpc, but that apparently uses an environment variable for the timeout, which would be a problem if you need to change the timeout for certain requests.

EDIT:

httpc:request/4 lets you specify a timeout as part of HTTPOptions, e.g.:

httpc:request(get, {URL, []}, [{timeout, timer:seconds(20)}], []).

Upvotes: 4

Related Questions