2012-11-21 38 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"; 
}