PHP Guzzle包 用法---鱼满仓
总结:
1.GUZZLE包最终还是用的curl的curl_exec和curl_multi_exec去请求,可以添加自定义配置,这些配置最终还是会对应到
curl_setopt_array($easy->handle, $conf); 设置
2.还有一个就是可以做一些请求前或者请求返回后的中间件。介入请求的过程中处理$stack = new HandlerStack();
push,handler进去
//使用默认配置去构建客户端
$client = new Client();
//设置CURL,使用去构建客户端
$client = new GuzzleHttpClient([
'curl' => [
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 1,
]
]);
//代理设置
$proxy = [
//http域名代理
'http' => config('app.fileserver_proxy') . ':' . config('app.fileserver_port'), // Use this proxy with "http"
//https域名代理
'https' => config('app.fileserver_proxy') . ':' . config('app.fileserver_port'), // Use this proxy with "https",
//不需要代理的域名
'no' => ''
];
$response = $client->request('GET','https://www.baidu.com', [
'proxy' => $proxy
]);
//异步请求,要用wait才能返回
$promise = $client->requestAsync('GET', 'https://www.baidu.com');
$promise = $promise->then(
function (ResponseInterface $res) {
dd($res->getBody());
echo $res->getStatusCode() . "n";
},
function (RequestException $e) {
dd($e);
echo $e->getMessage() . "n";
echo $e->getRequest()->getMethod();
}
)->wait();
dd($promise);
//自定义handler,并且增加请求中间件,前置处理
function add_response_header($header, $value)
{
return function (callable $handler) use ($header, $value) {
return function (
RequestInterface $request,
array $options
) use ($handler, $header, $value) {
$promise = $handler($request, $options)
return $promise->then(
function (ResponseInterface $response) use ($header, $value) {
return $response->withHeader($header, $value);
}
);
}
};
}
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(add_response_header('X-Foo', 'bar'));
$client = new Client(['handler' => $stack]);
---来自腾讯云社区的---鱼满仓

微信扫一扫打赏
支付宝扫一扫打赏