为什么我的REST请求返回垃圾数据?

时间:2010-05-26 15:30:03

标签: perl json rest lwp

我正在尝试使用LWP :: Simple向REST服务发出GET请求。这是简单的代码:

use LWP::Simple;
$uri = "http://api.stackoverflow.com/0.8/questions/tagged/php";
$jsonresponse= get $uri;
print $jsonresponse;

在我的本地计算机上运行Ubuntu 10.4和Perl版本5.10.1:

   @ farhan-lnx:〜$ perl --version
  这是为x86_64-linux-gnu-thread-multi

构建的perl,v5.10.1(*)

我可以得到正确的答案并将其打印在屏幕上。 E.g:

   @ farhan-lnx:〜$ head -10 output.txt
  {
   “总计”:1000,
   “page”:1,
   “pagesize”:30,
   “问题”:[
     {
       “标签”:[
         “PHP”,
         “阵列”,
         “编码式”
  (......剪断......)

但是在我上主机的机器上,我在屏幕上打印了 garbage 以获得相同的代码。我假设它与编码有关,但REST服务不会在响应中返回字符集类型,那么如何强制LWP :: Simple使用正确的编码?任何想法可能会发生在这里?

这是我主持人机器上的Perl版本:

  

[dredd] $ perl --version
  这是为x86_64-linux-gnu-thread-multi

构建的perl,v5.8.8

2 个答案:

答案 0 :(得分:4)

我碰巧有一个64位的RHEL 5.4盒子,上面有Perl 5.8.8。我拿了你的代码得到了完全相同的结果。我尝试使用Data::Dumper转储数据,但这并没有改变任何东西。然后我去了命令行并做了这个:

 wget -O jsonfile http://api.stackoverflow.com/0.8/questions/tagged/php
 --2010-05-26 11:42:41--  http://api.stackoverflow.com/0.8/questions/tagged/php
 Resolving api.stackoverflow.com... 69.59.196.211
 Connecting to api.stackoverflow.com|69.59.196.211|:80... connected.
 HTTP request sent, awaiting response... 200 OK
 Length: 5430 (5.3K) [application/json]
 Saving to: `jsonfile'
 2010-05-26 11:42:42 (56.9 KB/s) - `jsonfile' saved [5430/5430]

当我这样做时:

 file jsonfile

我得到了:

jsonfile: gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT), max speed

因此,JSON数据被Web服务器gzip压缩。我试过这个:

gzip -dc jsonfile

并且看到结果是您期望的JSON数据。

您现在可以做的是使用其他模块解压缩数据,或you can check out this other thread which shows how to accept gzip using LWP::UserAgent and handle the request that way

答案 1 :(得分:3)

这是bug 44435。将libwww-perl升级到5.827或更高版本。