2012-11-21 41 views
3

有没有办法从使用LWP创建的HTTP请求中获取未经修改的原始响应头?这是一个诊断工具,需要识别可能格式错误的标题的问题。从LWP获取原始响应头文件?

我发现的最接近的是:

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

但其实这解析头,然后从分析数据,并将其重建的规范化,清理后的版本。我真的需要完整的标题文本,它完全以服务器返回的形式出现,因此任何格式错误或非标准的东西都将清晰可辨。

如果事实证明没有办法用LWP来做到这一点,那么是否有其他的Perl模块可以做到这一点?

回答

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 [email protected]; 
$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; 
2

根据对HTTP::Response对象(及其包含的HTTP::Headers对象)的检查,标头在解析时会被丢弃。

我建议你试试WWW::Curl来代替。

EDIT片段使用WWW ::卷曲:

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"; 
}