<?php /** * Created by PhpStorm. * User: Zero * Date: 2020/8/19 * Time: 9:06 */ namespace Meibuyu\Micro\Shopify\tools; use GuzzleHttp\HandlerStack; use Hyperf\Guzzle\ClientFactory; use Hyperf\Guzzle\HandlerStackFactory; use Psr\Http\Message\ResponseInterface; /** * json格式请求 * Class HttpRequestJson * @package Meibuyu\Micro\Tools */ class HttpRequestJson { /** * @var ClientFactory */ private $clientFactory; /** * @var HandlerStack */ private $stack; public function __construct(ClientFactory $clientFactory) { $this->clientFactory = $clientFactory; $factory = new HandlerStackFactory(); $this->stack = $factory->create(); } /** * get请求 * @param $url * @param array $httpHeaders * @return ResponseInterface */ public function get($url, $httpHeaders = []) { $client = $this->clientFactory->create(['timeout' => 60, 'handler' => $this->stack,]); $res = $client->get($url, ['headers' => $httpHeaders]); return $this->processResponse($res); } /** * post请求 * @param $url * @param $data * @param array $httpHeaders * @return ResponseInterface */ public function post($url, $data, $httpHeaders = []) { $client = $this->clientFactory->create(['timeout' => 60, 'handler' => $this->stack,]); $res = $client->post($url, ['headers' => $httpHeaders, 'json' => $data]); return $this->processResponse($res); } /** * put请求 * @param $url * @param $data * @param array $httpHeaders * @return ResponseInterface */ public function put($url, $data, $httpHeaders = []) { $client = $this->clientFactory->create(['timeout' => 60, 'handler' => $this->stack,]); $res = $client->put($url, ['headers' => $httpHeaders, 'json' => $data]); return $this->processResponse($res); } /** * delete请求 * @param $url * @param array $httpHeaders * @return ResponseInterface */ public function delete($url, $httpHeaders = []) { $client = $this->clientFactory->create(['timeout' => 60, 'handler' => $this->stack,]); $res = $client->delete($url, ['headers' => $httpHeaders]); return $this->processResponse($res); } /** * 处理响应 * @param ResponseInterface $response * @return mixed */ public function processResponse($response) { $code = $response->getStatusCode(); $headers = $response->getHeaders(); $content = $response->getBody()->getContents(); return [$code, $headers, $content]; } }