简体   繁体   中英

Perl how to parse HTTP response content

I have a Perl script that does a post to a website to add a customer for billing purposes. That parts works great and I am able to test for errors/success. Now I need to parse the content that is returned.

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 -

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

I need to parse the result and return just specific fields, but I am not sure how to do that. Or is there a way that I can just pull ok specific value pairs from the content?

Assuming the line breaks in the output you posted were added by you rather than being in the returned string, the response's content appears to be in the application/x-www-form-urlencoded format.

You could (mis-)use URI to parse it.

use URI qw( );

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

The last hackish solution involves URI::Escape 's uri_unescape .

use URI::Escape qw( uri_unescape );

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM