Erlang:ibrowse - 获取重定向的URL

时间:2012-09-19 13:05:56

标签: erlang

我正在使用ibrowse API for Erlang。问题是,当我尝试阅读重定向到另一个网页的网页时,它变成空白。关于如何跟踪追踪到最终页面的任何想法?

这就是我现在所拥有的:

get_web(Src) ->
    ibrowse:start(),
    {_,_,_,Body} = ibrowse:send_req(Src, [], get),
    Body.

由于

2 个答案:

答案 0 :(得分:3)

如果响应中包含301或302状态代码,则应遵循响应中的Location标题。

get_web({url,Src}) ->
  ibrowse:start(),
  {ok, Status, Head, Body} = ibrowse:send_req(Src, [], get),
  if
    Status =:= 200 ->
      Body;
    Status =:= 301 orelse Status =:= 302 ->
      get_web(get_location(Head))
  end.

get_location(Head) ->
  case lists:keyfind("Location", 1, Head) of
    false -> {url, error};
    URL -> {url, URL}
  end.

答案 1 :(得分:0)

如果有人偶然发现,我就是这样做的:

get_web({_,error}) ->
    error;

get_web({url,Src}) ->
    ibrowse:start(),
    {_,_,Head,Body} = ibrowse:send_req(Src, [], get),
    if
        length(Body) == 0 ->
            get_web(get_location(Head));
        true ->
            Body
    end.

get_location([]) ->
    {url,error};
get_location([{"Location",URL}|_]) ->
    {url,URL};
get_location([_|T]) ->
    get_location(T).