perl 如何在AnyEvent::HTTP中解码响应?

rdlzhqv9  于 2023-04-06  发布在  Perl
关注(0)|答案(1)|浏览(147)

我正在用AnyEvent::HTTP写一个简单的脚本,它并行地获取几个HTML页面。这个模块不做任何内容解码,它只提供回调的响应体和头。
什么是正确的方法来解码响应到Perl的Unicode字符串?我应该依赖于“Content-Type”头字段或 meta标记?

vu8f3i0k

vu8f3i0k1#

可以使用与LWP相同的模块:

use AnyEvent::HTTP qw(http_get);
use HTTP::Message;
use HTTP::Headers;
use HTTP::Response;
my $can_accept = HTTP::Message::decodable;
http_get(
    "https://apa.at/",
    headers => { 'Accept-Encoding' => $can_accept },
    sub {
        my ( $body, $hdr ) = @_;
        delete( $hdr->{URL} );
        my $status  = delete( $hdr->{Status} );
        my $reason  = delete( $hdr->{Reason} );
        my $headers = HTTP::Headers->new(%$hdr);
        my $resp = HTTP::Response->new( $status, $reason, $headers, $body );

        print $resp->decoded_content . "\n";
    }
);

(来源:How can I accept gzip-compressed content using LWP::UserAgent?

相关问题