2

WWW::Mechanize用来获取一个网页,其中包含一个谷歌地图小部件,该小部件从文本/事件流类型的单个响应中接收常量数据。

这种响应就像来自服务器的永无止境的响应,不断返回更新的数据以使小部件工作。

我试图找出如何从 Perl 中读取确切的响应。使用类似的东西:

my $mech = WWW::Mechanize->new;

# Do some normal GET and POST requests to authenticate and set cookies for the session

# Now try to get that text/event-stream response

$mech->get('https://some.domain.com/event_stream_page');

但这不起作用,因为响应永远不会结束。

每次服务器更新流时,我如何发出该请求并开始读取响应并使用该数据执行某些操作?

4

1 回答 1

4

找到了一种方法来做到这一点。使用来自 LWP 的处理程序, WWW::Mechanize从中继承:

$mech->add_handler (
    'response_data',
    sub {
        my ($response, $ua, $h, $data) = @_;
        # Your chunk of response is now in $data, do what you need
        # If you plan on reading an infinite stream, it's a good idea to clean the response so it doesn't grow infinitely too!
        $response->content(undef);
        # Important to return a true value if you want to keep reading the response!
        return 1;
    },
);
于 2016-06-13T00:23:59.830 回答