代码之家  ›  专栏  ›  技术社区  ›  Alienfluid

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

  •  1
  • Alienfluid  · 技术社区  · 16 年前

    我尝试使用lwp::simple向REST服务发出get请求。下面是简单的代码:

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

    在我的本地机器上,运行Ubuntu10.4和Perl5.10.1版本:

    farhan@farhan lnx:~$perl——版本
    这是Perl,v5.10.1(*)为x86_-linux-gnu-thread-multi构建的

    我能得到正确的回答,并把它印在屏幕上。例如。:

    farhan@farhan lnx:~$head-10 output.txt
    {
    “总数”:1000,
    “页面”:1,
    “页面化”:30,
    “问题”:
    {
    “标签”:
    “PHP”
    “数组”,
    “编码风格”
    (……剪断……

    但在我的主机上,我可以 垃圾 在屏幕上打印相同的精确代码。我假设它与编码有关,但是REST服务不返回响应中的字符集类型,那么如何强制LWP::Simple使用正确的编码?你知道这里会发生什么吗?

    以下是主机上Perl的版本:

    [dredd]$perl——版本
    这是Perl,v5.8.8,为x86_-linux-gnu-thread-multi构建的

    2 回复  |  直到 16 年前
        1
  •  4
  •   Community Mohan Dere    9 年前

    我碰巧有一个64位的RHEL5.4框,上面有Perl5.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

        2
  •  3
  •   daxim Fayland Lam    16 年前

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