如何使用LWP::UserAgent登录Perl并使用HTTP::Cookie检查Cookie值?
我正在尝试使用LWP::UserAgent在perl中自动化一个测试用例。我需要在登录应用程序后检查cookie值。 我尝试了以下示例perl脚本,但在打印时得到了哈希值输出:如何使用LWP::UserAgent登录Perl并使用HTTP::Cookie检查Cookie值?,perl,lwp,lwp-useragent,Perl,Lwp,Lwp Useragent,我正在尝试使用LWP::UserAgent在perl中自动化一个测试用例。我需要在登录应用程序后检查cookie值。 我尝试了以下示例perl脚本,但在打印时得到了哈希值输出: my $ua = LWP::UserAgent->new; $ua->agent("MyApp/0.1 "); my $req = HTTP::Request->new(POST => 'http://' . $test_IP . '/login'); $req->con
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1 ");
my $req = HTTP::Request->new(POST => 'http://' . $test_IP . '/login');
$req->content_type('application/x-www-form-urlencoded');
my $postdata = 'object={"login":{"username":"test","password":"test"}}';
$req->content($postdata);
print "REQUEST is";
print $req;
my $res = $ua->request($req);
print "RESPONSE is";
print $res;
# Check the outcome of the response
if ($res->is_success) {
print LOG $res->headers()->as_string();
}
else {
print $res->status_line, "\n";
}
my $cookie_jar = HTTP::Cookies->new();
print "cookie is";
$cookie_jar->extract_cookies( $res );
print $cookie_jar->extract_cookies( $res );
print $cookie_jar->as_string;
if( $cookie_jar->as_string =~ m/httponly/i )
{
print "Success";
}
else
{
print "FAILED";
}
REQUEST isHTTP::Request=HASH(0x69e85a0)RESPONSE isHTTP::Response=HASH(0x6aa1d98)cookie isHTTP::Response=HASH(0x6aa1d98)
已收到哈希值中的输出:
my $ua = LWP::UserAgent->new;
$ua->agent("MyApp/0.1 ");
my $req = HTTP::Request->new(POST => 'http://' . $test_IP . '/login');
$req->content_type('application/x-www-form-urlencoded');
my $postdata = 'object={"login":{"username":"test","password":"test"}}';
$req->content($postdata);
print "REQUEST is";
print $req;
my $res = $ua->request($req);
print "RESPONSE is";
print $res;
# Check the outcome of the response
if ($res->is_success) {
print LOG $res->headers()->as_string();
}
else {
print $res->status_line, "\n";
}
my $cookie_jar = HTTP::Cookies->new();
print "cookie is";
$cookie_jar->extract_cookies( $res );
print $cookie_jar->extract_cookies( $res );
print $cookie_jar->as_string;
if( $cookie_jar->as_string =~ m/httponly/i )
{
print "Success";
}
else
{
print "FAILED";
}
REQUEST isHTTP::Request=HASH(0x69e85a0)RESPONSE isHTTP::Response=HASH(0x6aa1d98)cookie isHTTP::Response=HASH(0x6aa1d98)
请建议我如何登录应用程序并检查所需的值(此处为cookie值)
但在打印时,我得到的是散列值输出
你说的是这些台词:
print "REQUEST is";
print $req;
my $res = $ua->request($req);
print "RESPONSE is";
print $res;
$req
和$res
都是对象。如果您打印一个对象,您将得到它所属的对象类型(“$req
”和“$res
”)。您还可以看到对对象的引用。当这两个类都将它们的对象实现为散列引用时,将显示两个散列引用
我不确定您希望看到什么,但有两种方法可以从对象中获取更有用的信息
$res->headers
和$res->status\u line
。这两个类都是的子类,因此它们都继承该类的as_string()
方法。因此,如果您只想查看作为HTTP请求发送的字符串或作为HTTP响应返回的字符串,可以调用$req->as_string()
或$res->as_string()
print Dumper$req
)会很有用
至于创建cookie罐,其概要相当清楚。您可以按您的方式创建一个cookie jar(几乎),然后通过调用UA的
cookie\u jar()
方法将其与UserAgent对象关联起来。但是您需要在创建UA后立即执行此操作—当然是在您使用UA发出任何请求之前。与您的输出无关,但您在发出请求后正在制作一个新的cookie jar。您应该在$ua
@simbabque中使用cookie jar对象。您可以分享更多关于如何在$ua
中使用cookie jar对象的详细信息吗