Search code examples
perlencodinglwp

So LWP::UserAgent can automatically detect the charset?


  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));

The above code converts the response to UTF-8 encoding,without the need to tell it which encoding the response is using.

I asume this may fail under certain cases.

How can I explicitly tell LWP::UserAgent the response encoding?


Solution

  • See the docs for decoded_content in HTTP::Message:

    $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.