在 header 带 token 的 Guzzle Http Request 模板

单纯纪录自己用的 Guzzle Request 模板

简单版

use GuzzleHttp\Client;$client = new GuzzleHttp\Client(['base_uri' => 'https://api.example/']);$token = '<TOKEN>';$method = 'GET';$url = 'v1.3/products';$headers = ['Authorization' => 'Bearer ' . $token];//$headers must be an array$response = $client->request($method, $url, ['headers' => $headers]);dd(json_decode($response->getBody(),true));

try & catch 版

use GuzzleHttp\Client as Client;use GuzzleHttp\Psr7\Request as Request;use GuzzleHttp\Exception\ClientException as ClientException;$client = new Client(['base_uri' => 'https://api.example/']);$token = '<TOKEN>'$method = 'POST';$url = 'URL'$header = ['Authorization'=>'Bearer '.$token, 'Content-Type'=>'application/json'];$body = 'BODY';$request = new Request($method, $url, $header, $body);try{$response = $client->send($request);dd(json_decode($response->getBody(),true));} catch (ClientException $e){dd(json_decode($e->getResponse()->getBody(),true));}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章