从LWP获取原始响应标头?

时间:2012-11-21 02:35:13

标签: perl http-headers lwp

有没有办法从LWP发出的HTTP请求中获取原始的,未修改的响应头?这适用于需要识别可能格式错误的标头问题的诊断工具。

我发现最接近的是:

use LWP::UserAgent;
my $ua = new LWP::UserAgent;
my $response = $ua->get("http://somedomain.com");
print $response->headers()->as_string();

但是这实际上解析了标题,然后从解析的数据中重构了它们的规范化,清理后的版本。我确实需要完整的服务器返回形式的整个标题文本,因此任何格式错误或非标准的都可以清楚识别。

如果事实证明LWP无法做到这一点,是否有其他Perl模块可以做到这一点?

2 个答案:

答案 0 :(得分:6)

Net::HTTP以较少的处理提供较低级别的访问权限。由于它是IO::Socket::INET的子类,因此您可以在发出请求后直接从对象中读取。

use Net::HTTP;

# Make the request using Net::HTTP.
my $s = Net::HTTP->new(Host => "www.perl.com") || die $@;
$s->write_request(GET => "/", 'User-Agent' => "Mozilla/5.0");

# Read the raw headers.
my @headers;
while(my $line = <$s>) {
    # Headers are done on a blank line.
    last unless $line =~ /\S/;
    push @headers, $line;
}
print @headers;

答案 1 :(得分:2)

基于对HTTP::Response对象(及其包含的HTTP::Headers对象)的检查,标题在解析时将被丢弃。

我建议您尝试使用WWW::Curl

编辑使用WWW :: Curl的片段:

use WWW::Curl::Easy;

my ($header, $body);

my $curl = WWW::Curl::Easy->new;
$curl->setopt(CURLOPT_URL, $url_to_get); # get this URL
$curl->setopt(CURLOPT_WRITEHEADER, \$header); # save header text in this var
$curl->setopt(CURLOPT_WRITEDATA, \$body); # save body text in this var

my $code = $curl->perform;
if (0 == $code) {
  # header text is in $header, body text in $body 
} else {
  print $curl->strerror($code).": ".$curl->errbuf."\n";
}