【问题标题】:Perl how to parse HTTP response contentPerl如何解析HTTP响应内容
【发布时间】:2015-11-04 03:43:56
【问题描述】:

我有一个 Perl 脚本,它向网站发布帖子以添加客户以进行计费。该部分效果很好,我能够测试错误/成功。现在我需要解析返回的内容。

use strict;
use warnings;

use LWP::UserAgent;

my $ua = LWP::UserAgent->new;
my $res = $ua->post('https://testserver', [
    'UMkey' => "test key",
    'UMname' => "Example Tester",
    'UMcard' => "4000100011112224",
    'UMexpir' => "0919",
    'UMcvv2' => "123",
    'UMamount' => "5.50",
    'UMinvoice' => "123456",
    'UMstreet' => "1234 Main Street",
    'UMzip' => "12345",
    'UMcommand' => 'cc:sale',
    'UMaddcustomer' => 'yes',
    'UMbillcompany' => 'ed',
    'UMbillfname' => 'Tester',
    'UMbilllname' => 'Tofu',
]);

print "\n\nresult: ".$res->content;
print "\n";

结果-

result: UMversion=2.9&UMstatus=Approved&UMauthCode=006444&UMrefNum=100020848&UMa
vsResult=Address%3A%20Match%20%26%205%20Digit%20Zip%3A%20Match&UMavsResultCode=Y
YY&UMcvv2Result=Match&UMcvv2ResultCode=M&UMresult=A&UMvpasResultCode=&UMerror=Ap
proved&UMerrorcode=00000&UMcustnum=50405&UMbatch=309&UMbatchRefNum=1640&UMisDupl
icate=N&UMconvertedAmount=&UMconvertedAmountCurrency=840&UMconversionRate=&UMcus
tReceiptResult=No%20Receipt%20Sent&UMprocRefNum=&UMcardLevelResult=A&UMauthAmoun
t=5.5&UMfiller=filled

我需要解析结果并只返回特定字段,但我不知道该怎么做。或者有没有一种方法可以让我从内容中提取好的特定值对?

【问题讨论】:

    标签: perl


    【解决方案1】:

    假设您发布的输出中的换行符是您添加的,而不是在返回的字符串中,则响应的内容似乎是application/x-www-form-urlencoded 格式。

    您可以(错误地)使用URI 来解析它。

    use URI qw( );
    
    my %response_data = URI->new("?".$response->content(), "http")->query_form();
    

    最后一个hackish解决方案涉及URI::Escapeuri_unescape

    use URI::Escape qw( uri_unescape );
    
    my %response_data = map { uri_unescape($_) } split(/[&=]/, $response->content());
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 2017-12-28
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      相关资源
      最近更新 更多