幾個使用 LWP (WWW::Mechanize) 的好習慣...

WWW::Mechanize 是繼承 libwww-perl 中 LWP::UserAgent 的工具,所以這個方式通用於兩者...

首先是在取得資料時加上 Accept-Encoding: gzip 的 header,這可以在產生物件時指定,之後就都會送出:

my $ua = LWP::UserAgent->new;
$ua->default_header('Accept-Encoding' => 'gzip');

取回後直接透過 HTTP::Response 的 decoded_content 幫你處理:

my $res = $ua->get($uri);
my $msg = $res->decoded_content;

取回的 $msg 會是 Perl internal encoding,要變成 UTF-8 還需要透過 Encodeencode('utf8', $msg)

這樣只要 server-side 有支援 gzip 就會自動壓縮並且在本地端解開,沒壓縮也沒關係,HTTP::Response 會依照 Content-Type 處理。

Updateclkao 指出 WWW::Mechanize 預設值就會包括 gzip 設定,剛剛拿 code.jquery.com 測試沒錯。

2 thoughts on “幾個使用 LWP (WWW::Mechanize) 的好習慣...”

  1. I thought gzip in request is default for mechanize if you have zlib? see WWW::Mechanize::_modify_request

Leave a Reply

Your email address will not be published. Required fields are marked *