工作中经常用到脚本发送http请求,但是用脚本发送和用浏览器发送差别很到,当你用脚本调用一些接口时可能没有权限,此时需要获取到调用接口的权限,一般情况下就是。请求的时候需要带着一个cookie值或者一个token值,浏览器发送时一般都会保存这个值,但是脚本发送不知道保存在那个地方还是不会生成(知道的小伙伴告诉我一声),但是一般的做法是带着用户名和密码去请求,服务器给你回复一个cookie值,然后下一次调用接口的时候就带着这个cookie值去请求;
获取cookie值
```
sub getCookie{
my($ip,$port)=@_;
my $ua = LWP::UserAgent->new(
protocols_allowed => [ 'http', 'https' ],
timeout => 30,
ssl_opts => { verify_hostname => 0},
);
$username='admin';
$password='admin';#密码有没经过加密处理,如果经过加密处理要写加密后的
my $arg={
'username' => $username,
'password' => $password,
};
$url="https://$ip:$port/vapi/extjs/access/ticket";#url可以抓包获取,不是登录的那个地址
my $resp = $ua->post($url,$arg,'Content_Type' => 'form-data');#用post方法提交参数
my $status=$resp->status_line;
my $header=$resp->headers_as_string;#解析头部
my $content = $resp->content;
if ($status=~ /200/)
{
@array=split(/\n/,$header);
foreach $rock (@array)
{
if ($rock=~/^Set-Cookie/)
{
@Setcookie=split(/\s+/,$rock);
$Setcookie[1]=~s/;$//;
my $cookie=$Setcookie[1];
$content=$cookie;
last;
}
}
}
return $content;
}
发送get请求
调用上面的getcookie函数,获取cookie值
sub https_Get {
my ( $url,$cookie) = @_;
my $ua = LWP::UserAgent->new(
protocols_allowed => [ 'http', 'https' ],
timeout => 30,
ssl_opts => { verify_hostname => 0 },
);
$ua->default_header('cookie' => "$cookie" );
my $response = $ua->get($url);
return $response->{_content};
}
发送post请求
sub https_Post{
my($url,$arg,$cookie) = @_; #arg为需要提交的参数
my $ua = LWP::UserAgent->new(
protocols_allowed => [ 'http', 'https' ],
timeout => 30,
ssl_opts => { verify_hostname => 0},
);
$ua->default_header('cookie' => "$cookie" );
$resp = $ua->post($url,$arg,'Content_Type' => 'form-data'); #注意参数的格式是form-data还是其他格式,可用postman(一款模拟发送http请求的插件,只可以在谷歌浏览器中用)调试
$content = $resp->content;
return $content;
}