只需要读取页面的一部分(n个字节)并关闭连接,如何在AnyEvent::HTTP上执行此操作?

最佳答案

当块到达时,on_body被重复调用。从on_body返回false将终止下载。

sub my_http_request {
   my $cb = pop;
   my ($method, $url, %args) = @_;

   croak("Unsupported: on_body")          if $args{on_body};
   croak("Unsupported: want_body_handle") if $args{want_body_handle};

   my $max_to_read = delete($args{max_to_read});

   my $data;
   return http_request(
      $method => $url,
      %args,
      on_body => sub {
         #my ($chunk, $headers) = @_;
         $data .= $_[0];
         return !defined($max_to_read) || length($data) < $max_to_read;
      },
      sub {
         my (undef, $headers) = @_;
         $cb->($data, $headers);
      },
   );
}

my_http_request一样使用http_request,除了它接受可选的max_to_read参数。

例如,
my $cb = AnyEvent->condvar();
my_http_request(
   GET => 'http://...',
   ...
   max_to_read => ...,
   $cb,
);

my ($data, $headers) = $cb->recv();

例如,
my $done = AnyEvent->condvar();
my_http_request(
   GET => 'http://...',
   ...
   max_to_read => ...,
   sub {
      my ($data, $headers) = @_;
      ...
      $done->send();
   },
);

$done->recv();

关于perl - 如何使用AnyEvent::HTTP仅获取页面的一部分?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43355138/

10-11 14:35