如何在 Perl 中找到链接的内容类型?

问题描述 投票:0回答:2

假设您获得了一个 URL,http://site.com。您如何在不下载的情况下找出它的内容类型? Perl 的WWW::MechanizeLWP 可以发出 HEAD 请求吗?

perl content-type
2个回答
9
投票

您可以按照以下方式使用LWP的

head()
方法

use LWP::UserAgent;
$ua = LWP::UserAgent->new;
$ua->head('<url>');

4
投票

这是一个使用 LWP 的完整示例。如果您在列表上下文中使用调用

content_type
,您将获得类型和字符集作为单独的值:

use v5.10;

my $url = 'https://www.perl.com';

use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $response = $ua->head( $url );
my( $type, $charset ) = $response->content_type;
say "LWP: Content type is ", $type;
say "LWP: charset is ", $charset;

Mojolicious 中有同样的东西,它不会为您分解

Content-type
标题。

use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $tx = $ua->head( $url );
my( $type, $charset ) =
    split /\s*;\s*/, $tx->result->headers->content_type, 2;
say "Mojo: Content type is ", $type;
say "Mojo: charset is ", $charset;

一些服务器在 HEAD 请求上阻塞,所以当我这样做并得到任何类型的错误时,我用 GET 请求重试它并且只请求资源的前几百个字节。

© www.soinside.com 2019 - 2024. All rights reserved.