如何使用 LWP::UserAgent 接受 gzip 压缩内容?
我正在使用 Perl 的 LWP::UserAgent
通过 Web 获取一些页面,并且希望尽可能礼貌。 默认情况下,LWP::UserAgent
不会通过 gzip 无缝处理压缩内容。 有没有一种简单的方法可以做到这一点,为每个人节省一些带宽?
I am fetching some pages over the Web using Perl's LWP::UserAgent
and would like to be as polite as possible. By default, LWP::UserAgent
does not seamlessly handle compressed content via gzip. Is there an easy way to make it do so, to save everyone some bandwidth?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
LWP 内置了此功能,这要归功于
HTTP::Message
。 但它有点隐藏。首先确保您已安装
Compress::Zlib
你可以处理gzip
。HTTP::Message::decodable ()
将根据您已安装的模块输出允许的编码列表; 在标量上下文中,此输出采用逗号分隔的字符串形式,您可以将其与“Accept-Encoding
”HTTP 标头一起使用,该标头LWP
要求您添加到HTTP::Request
-s 自己。 (在我的系统上,安装了Compress::Zlib
,列表为“gzip
、x-gzip
、deflate
”。)当您的
HTTP::Response
返回,请务必使用$response->decoded_content 访问内容
而不是$response->content
。在
LWP::UserAgent
中,所有这些都像this:这也会将文本解码为 Perl 的 unicode 字符串。 如果您仅想要
LWP
解压缩响应,而不是弄乱文本,这样做:LWP has this capability built in, thanks to
HTTP::Message
. But it's a bit hidden.First make sure you have
Compress::Zlib
installed so you can handlegzip
.HTTP::Message::decodable()
will output a list of allowed encodings based on the modules you have installed; in scalar context, this output takes the form a comma-delineated string that you can use with the 'Accept-Encoding
' HTTP header, whichLWP
requires you to add to yourHTTP::Request
-s yourself. (On my system, withCompress::Zlib
installed, the list is "gzip
,x-gzip
,deflate
".)When your
HTTP::Response
comes back, be sure to access the content with$response->decoded_content
instead of$response->content
.In
LWP::UserAgent
, it all comes together like this:This will also decode text to Perl's unicode strings. If you only want
LWP
to uncompress the response, and not mess with the text, do like so: