【问题标题】:So LWP::UserAgent can automatically detect the charset?那么 LWP::UserAgent 可以自动检测字符集吗?
【发布时间】:2011-06-29 08:45:13
【问题描述】:
  our $ua = LWP::UserAgent->new;
  my $response = $ua->get($url);
  if($response->is_success) {
    my $perl_hash_or_arrayref = decode_json(encode("UTF-8", $response->decoded_content));

以上代码将响应转换为UTF-8编码,无需告诉它响应使用的是哪种编码。

我认为这在某些情况下可能会失败。

如何明确告诉LWP::UserAgent 响应编码?

【问题讨论】:

    标签: perl encoding lwp


    【解决方案1】:

    HTTP::Message 中查看decoded_content 的文档:

    $mess->decoded_content(%options)

        Returns the content with any Content-Encoding undone and for
     textual content the raw content encoded to Perl's Unicode strings.
     If the Content-Encoding or charset of the message is unknown this
     method will fail by returning undef.
    
        The following options can be specified.
    
        charset
    
            This override the charset parameter for text content. The value
     none can used to suppress decoding of the charset.
    

    【讨论】:

    • If the Content-Encoding or charset of the message is unknown this method will fail by returning undef.,但实际上它有效,只是我不知道内部原理。
    • @new_perl:LWP 只查看您正在与之通信的 HTTP 服务器发送的 Content-EncodingCharset HTTP 标头。
    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 2010-09-25
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2021-02-09
    相关资源
    最近更新 更多