guzzle的使用
2020-04-23 本文已影响0人
PENG先森_晓宇
guzzle包是一个类似curl功能的composer。guzzle是一个php的http客户端,可用于php调用第三方接口等。
安装
推荐使用composer安装
composer require guzzlehttp/guzzle
使用
- 客户端实例化
$client = new \GuzzleHttp\Client();
- 客户端请求接口
$response = $client->request('GET', 'url');
$response= $client->get('url');//GET方式
$response= $client->post('url');//POST方式
- 返回respone的状态吗
echo $response->getStatusCode(); # 200
- 返回接口相应数据。一定要调用getContents()方法
$response->getBody()->getContents();
有时候$response->getBody()->getContents(); 返回为空,使用下面代码
$response->getBody()->rewind();
$response->getBody()->getContents();
- get方式调用
url后面可以直接拼接上参数
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appSecrect}";
$client = new Client();
$respone = $client->request('GET', $url);
dd($respone->getBody()->getContents());
- get方式设置头
$response = $client->get('https://api.github.com/user',[
'headers'=>[
'Accept'=>'application/json',
'Authorization'=>'token '.$accessToken
]
]);
- post方式form-data传参
$client = new Client();
$response = $client->request('POST', 'url', [
"form_params" => [
"img" => $payload['img_flow'],
'type' => 1
]
]);
dd($respone->getBody()->getContents());
- post方式设置header
$response = $client->post($getTokenUrl, [
'headers'=>['Accept'=>'application/json'],
"form_params" => [
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'code' => $code,
'redirect_uri' => env('REDIRECT_URl'),
]
]);
- post方式json传参
$param = '{
"touser":"oXgNt5Tsr-C4UjV1y6dE2nBOdHdk",
"mp_template_msg":{
"appid":"wx0dad7075223c2faf",
"template_id":"j16ZBrZfNQFYRVYOGLF62xTBJN1z3-s-XwtS5NUJkR8",
"url":"http://weixin.qq.com/download",
"miniprogram":{
"appid":"wxb9440546a1a6bde2",
"pagepath":"index?foo=bar"
},
"data":{
"first":{
"value":"支付成功",
"color":"#173177"
},
"keyword1":{
"value":"24324353535",
"color":"#173177"
},
"keyword2":{
"value":"39.8元",
"color":"#173177"
}
}
}
}';
$client=new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response=$client->post($url,[
'body'=>$param
]);
dd($respone->getBody()->getContents());
或者是下面这种,建议是下面这种调用。这种方式代表该接口传的参数是json,而如果想上面那种调用的话则是所有的接口的参数都是json。
$client=new Client();
$response=$client->post($url,[
'headers' => [ 'Content-Type' => 'application/json' ],
'body'=>$param
]);
return $response->getBody()->getContents();
- post方式x-www-form-urlencoded方式传参
$client=new Client();
$response=$client->post($url,[
'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded' ]
'body'=>$xml
]);
dd($respone->getBody()->getContents());
- post方式xml传参
$client=new Client([
'
]);
$response=$client->post($url,[
'headers' => [ 'Content-Type' => 'text/xml' ],
'body'=>$xml
]);
dd($respone->getBody()->getContents());
常见问题
- 报"Class 'Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory' not found"
1.首先取下guzzle包: composer remove guzzlehttp/guzzle
- composer dump-autoload
- 最后重新安装它:composer require guzzlehttp/guzzle