2015-11-03 82 views
0

我有一個Perl腳本,用於向網站發佈帖子以添加客戶用於計費目的。這部分工作很好,我可以測試錯誤/成功。現在我需要解析返回的內容。Perl如何解析HTTP響應內容

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

假設您發佈的輸出中的換行符是由您添加的,而不是位於返回的字符串中,則回覆的內容顯示爲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());