在Laravel中向外部API发送HTTP请求

5 浏览
0 Comments

在Laravel中向外部API发送HTTP请求

我想通过向外部 API 发送 HTTP 请求(例如使用 jQuery 的 AJAX)获取一个对象。如何开始呢?我在 Google 上进行了研究,但是我找不到任何有帮助的内容。

我开始怀疑这是否可能?

在这篇帖子Laravel 4 make post request from controller to external url with data中看起来可以做到。但是没有示例或任何来源可以找到一些文档。

请帮帮我?

admin 更改状态以发布 2023年5月24日
0
0 Comments

我们可以在 Laravel 中使用 Guzzle 包,它是一个 PHP HTTP 客户端,用于发送 HTTP 请求。

您可以通过 Composer 安装 Guzzle。

composer require guzzlehttp/guzzle:~6.0

或者您可以在现有的 composer.json 中将 Guzzle 指定为项目的依赖项。

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

在 Laravel 5 中使用 Guzzle 的示例代码如下所示:

use GuzzleHttp\Client;
class yourController extends Controller {
    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);
        echo $res->getStatusCode();
        // 200
        echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
        echo $res->getBody();
        // {"type":"User"...'
}

0
0 Comments

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

看看Guzzle

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

0