使用 WWW::Mechanize 或 LWP::UserAgent 获取 text/event-stream 网络响应

Fetch text/event-stream web response using WWW::Mechanize or LWP::UserAgent

我正在使用 WWW::Mechanize 获取包含 Google 地图小部件的网页,该小部件从类型为 text/event-stream 的单个响应接收常量数据。

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

我正在尝试了解如何从 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');

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

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

找到了一种方法来做到这一点。使用 handler from LWP, from which 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;
    },
);