logo听风亭

如风在野,山峦共听

guzzlehttp/guzzle 使用示例

1     扩展类实例化 
$this->client = new Client();
2 get请求
$resp = $this->client->request('GET', $url ,['query'=>$request_data]); //参数一 请求方式 GET | POST ;参数二 地址 ;参数三 请求参数 数组格式 ['query'=>array(请求参数)]  ; query 为数据包类型
$result = json_decode($resp->getBody(), true); //获取返回数据
if($result['code']){
    throw new \Exception($result['msg']);
}
3 post请求
$resp = $this->client->request('POST', $url, ['form_params' => ['filter' => $filter]]); //参数一 请求方式 GET | POST ;参数二 地址 ;参数三 请求参数 数组格式 ;数据包 类型 body|json|form_params|multipart|cookies
$result = json_decode($resp->getBody(), true); //获取返回数据
if($result['code']){
    throw new \Exception($result['msg']);
    // $this->error($result['msg']);
}
4扩展
将接受到的图片地址1 修改为图片地址2
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$imgUrl = env('DOMAIN_IMGUrl'); //图片地址
$localUrl = env('DOMAIN_LOCALURL'); //替换地址
$stack->push($this->modifyResponseContent($imgUrl, $localUrl));
$this->client = new Client(['handler' => $stack]);
/**
* 更改响应内容,替换图片地址
*/
private function modifyResponseContent($str, $value){
    return function (callable $handler) use ($str, $value) {
        return function (
            RequestInterface $request,
            array $options
        ) use ($handler, $str, $value) {
            $promise = $handler($request, $options);
            return $promise->then(
                function (ResponseInterface $response) use ($str, $value) {
                    $body = str_replace($str, $value, $response->getBody());
                    $stream = Utils::streamFor($body);
                    return $response->withBody($stream);
                }
            );
        };
    };
}


Comments 0

0.100784s