有些时候我们的 post、get 请求可能需要带上特定的 cookie;
一般情况见于模拟各种登录的情况。
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception;
use GuzzleHttp\Cookie\CookieJar;
function cookie_post($url, $data=null){
$res = [];
if(!is_null($data)){
$params = [];
foreach($data as $key => $value){
array_push($params, $key."=".$value);
}
$target_url = $url."?".join("&", $params);
}
try{
$jar = new \GuzzleHttp\Cookie\CookieJar;
$client = new \GuzzleHttp\Client(['headers' => [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0',
'Accept-Encoding' => 'gzip, deflate',
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With' => "XMLHttpRequest"
]]);
$response = $client->request('POST', $target_url, ['cookies' => $jar]);
$res = json_decode($response->getBody()->getContents());
}catch (\Exception $e){
Log::error("cookie post response get failed! target url: ".$url);
}finally{
return $res;
}
}
(文章今日已有 1 人访问,总访问量 4 ::>_<::)