2013-01-03 53 views
2

我开发这个功能:附加超时以http:请求

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. 

现在我想添加超时的概念在请求后,例如20秒。我想从服务器

我试图显示错误:

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. 

回答

3

我推荐使用ibrowse作为HTTP客户端。它包含send_req/6中的超时参数(以及用于更多微调超时的选项)。它通常比默认包含的inets库更高效。

另一种选择是​​,但显然使用环境变量作为超时时间,如果您需要更改某些请求的超时时间,这会是一个问题。

编辑:

httpc:request/4允许您指定超时为

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

感谢HTTPOptions的一部分,例如:,我会尝试用这种代码 –