Perl如何解析HTTP响应内容

时间:2015-11-03 19:29:44

标签: perl

我有一个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

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

1 个答案:

答案 0 :(得分:1)

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

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

use URI qw( );

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

最后一个hackish解决方案涉及URI::Escape' uri_unescape

use URI::Escape qw( uri_unescape );

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