【问题标题】:add timeout with http:request使用 http:request 添加超时
【发布时间】:2013-12-16 21:13:01
【问题描述】:

我开发了这个功能:

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.

【问题讨论】:

    标签: erlang


    【解决方案1】:

    我建议使用ibrowse 作为您的 HTTP 客户端。它在 send_req/6 中包含一个超时参数(以及更多微调超时的选项)。它通常也比默认包含的 inets 库更有效。

    另一个选项是lhttpc,但这显然使用环境变量来设置超时,如果您需要更改某些请求的超时,这将是一个问题。

    编辑:

    httpc:request/4 允许您将超时指定为 HTTPOptions 的一部分,例如:

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

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 1970-01-01
      • 2015-06-27
      • 2017-10-21
      • 2010-10-22
      • 2011-07-16
      • 2015-10-22
      • 2011-11-30
      • 2014-10-16
      相关资源
      最近更新 更多