在某些同步批量的业务场景要用到请求实现,但是用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;
|