从 Laravel 向外部 API 发出 HTTP 请求

新手上路,请多包涵
阅读 754
2 个回答

基于此处类似问题的答案: https ://stackoverflow.com/a/22695523/1412268

看看 古驰

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....

原文由 AI Snoek 发布,翻译遵循 CC BY-SA 3.0 许可协议

Laravel v7.X 开始,该框架现在带有一个围绕 Guzzle HTTP 客户端 的最小 API。它提供了一种使用 HTTP 客户端 进行 getpostputpatchdelete 请求的简单方法:

 use Illuminate\Support\Facades\Http;

$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');

您可以使用返回的 Illuminate\Http\Client\Response 实例提供的一组方法来管理响应。

 $response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

请注意,您当然需要像这样安装 Guzzle:

 composer require guzzlehttp/guzzle

内置了更多有用的功能,您可以在此处找到有关这些功能集的更多信息: https ://laravel.com/docs/7.x/http-client

这绝对是现在在 Laravel 中进行外部 API 调用的最简单方法。

原文由 Syclone 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题