[软件测试] 使用GuzzleHttp快速入门及携带cookie

[复制链接]
发表于 2022-4-18 00:21:57
在某些同步批量的业务场景要用到请求实现,但是用curl显得有点慢,因此引入guzzlehttp来解决这个问题
发起同步请求并携带cookie
function doladall($url, $arr)
{
    //同步请求
    $client = new GuzzleHttp\Client();
    //设置cookie

    $domain = parse_url($url)['host'];
    $values = [
        'user_code' => 'xxx',
    ];
    $cookieJar = CookieJar::fromArray($values, $domain);
    $res = $client->request('POST', $url, [
        'cookies' => $cookieJar,
        'form_params' => $arr
//        'query' => $arr
    ]);
    echo $res->getBody();
}
发起异步请求并携带cookie
function syncpost($url, $arr)
{
    $client = new Client();

    //设置cookie
    $domain = parse_url($url)['host'];
    $values = [
        'user_code' => 'xxx',
    ];
    $cookieJar = CookieJar::fromArray($values, $domain);

    $request = new Request('POST', $url);
$promise = $client->sendAsync($request,['cookies' => $cookieJar,'form_params' => $arr])->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

}
模拟登录并获取cookie值
$arr = [
    'name'=>'xxx',
    'pwd'=>'xxx',
];
$client = new GuzzleHttp\Client(['base_uri' => 'http://localhost:9091/index/index/']);
$res = $client->request('POST', 'logincheck',[
    'form_params'=>$arr
]);
$head_arr = $res->getHeader('Set-Cookie');
$cookie_arr = [];
foreach ($head_arr as $val){
    $new_sub = explode('=',substr($val,0,strpos($val,';')));
    $cookie_arr[$new_sub[0]] = $new_sub[1];
}
var_dump($cookie_arr);exit;


上一篇:压缩备份数据库与网站数据(mysql不停止的方法)简易实用BAT
下一篇:emlog模板 文章密码页样式

使用道具 举报

Archiver|手机版|小黑屋|吾爱开源 |网站地图

Copyright 2011 - 2012 Lnqq.NET.All Rights Reserved( ICP备案粤ICP备14042591号-1粤ICP14042591号 )

关于本站 - 版权申明 - 侵删联系 - Ln Studio! - 广告联系

本站资源来自互联网,仅供用户测试使用,相关版权归原作者所有

快速回复 返回顶部 返回列表