我在向HotelsPro网络服务发送Restful请求时遇到问题。
我尝试使用基本凭据向此链接https://api-test.hotelspro.com:443发送请求,但每次“未提供身份验证凭据”时都会收到错误,尽管此凭据正在浏览器上运行。我的代码如下所示
sub getJSONdata {
my ($SupplierXMLServer, $message, $compressed,$timeOut) = ();
($SupplierXMLServer, $message, $compressed,$timeOut) = @_;
$SupplierXMLServer='https://api-test.hotelspro.com/api/v2/search/?destination_code=20b05&checkin=2016-11-09&checkout=2016-11-12¤cy=USD&client_nationality=PS&pax=2';
my $username = "Epilgrim";
my $password = "xxxxxxxxxx";
use LWP::UserAgent;
my $userAgent = LWP::UserAgent->new(agent =>"1");
$userAgent->credentials('https://api-test.hotelspro.com:443', 'api', $username , $password);
$userAgent->timeout($timeOut) if($timeOut); # in seconds
use HTTP::Request::Common;
my $response = '';
if($compressed){
$response = $userAgent->request( GET $SupplierXMLServer,
Content_Type => 'application/json',
Accept_Encoding => "gzip,deflate",
Content => $message);
}
else{
$response = $userAgent->request( GET $SupplierXMLServer,
Content_Type => 'application/json',
Content => $message);
}
return $response->error_as_HTML unless $response->is_success;
#return $response->content;
if($compressed){
return $response->decoded_content;
}
else{
return $response->content;
}
}
请帮我写出正确的代码并以正确的方式发送请求以获得有效的回复。
答案 0 :(得分:1)
给定的链接重定向到https://api-test.hotelspro.com/login/?next=/,它正在寻找基于表单的身份验证页面。但是在您的Perl脚本中,您正在尝试基本身份验证。请检查谷歌以了解Basic Auth vs Form Based Auth之间的区别。
现在,为了执行基于表单的身份验证,最好使用WWW :: Mechanize,它是LWP的包装,但提供了更方便的方法。以下是从WWW::Mechanize's official help page:
开始的基于表单的身份验证的示例代码 #!/usr/bin/perl -w -T
use strict;
use WWW::Mechanize;
my $login = "login_name";
my $password = "password";
my $folder = "folder";
my $url = "http://img78.photobucket.com/albums/v281/$login/$folder/";
# login to your photobucket.com account
my $mech = WWW::Mechanize->new();
$mech->get($url);
$mech->submit_form(
form_number => 1,
fields => { password => $password },
);
die unless ($mech->success);
# upload image files specified on command line
foreach (@ARGV) {
print "$_\n";
$mech->form_number(2);
$mech->field('the_file[]' => $_);
$mech->submit();
}
希望这有帮助!