【问题标题】:Doing HTTP requests FROM Laravel to an external API从 Laravel 向外部 API 发出 HTTP 请求
【发布时间】:2014-04-16 20:12:11
【问题描述】:

我想要的是从一个带有HTTP(例如,jQuery 的AJAX)请求的API 到一个外部API 的对象。我该如何开始?我对 Google 先生进行了研究,但找不到任何帮助。

我开始怀疑这是否可能? 在这篇文章Laravel 4 make post request from controller to external url with data 中看起来可以做到。但是没有示例,也没有任何来源可以找到一些文档。

请帮帮我?

【问题讨论】:

标签: php http laravel request


【解决方案1】:

根据此处类似问题的回答: 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", ....

【讨论】:

  • 另见 Jeremie Ges 的答案,看起来很棒,虽然它实际上并没有回答我关于 Laravel 的问题,但我一定会调查一下。谢谢!
  • @Chilion,Al Snoek 正在指导您使用 Laravel 官方软件包。它预装在 laravel 供应商组中。
  • 我得到一个 Stream 对象而不是 json 字符串。有人可以帮我吗?
  • 我做同样的事情,但我的浏览器无限转
  • 现在在 Laravel 7.x 中有一种更简单的方法:stackoverflow.com/a/60908329/2341298
【解决方案2】:

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

你可以通过 composer 安装 Guzzle

composer require guzzlehttp/guzzle:~6.0

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

{
   "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"...'
}

【讨论】:

  • 感谢您的回答。另请参阅我的帖子下方的评论;很久以后,创建了一个非常小的如何使用 Guzzle。从 aisnoek 他的回答。 chilion.nl/laravel-post-requests-with-guzzle – Chilion 8 月 19 日 12:09 √
  • 你的评论// "200"应该是// 200,因为返回的值是一个整数。
【解决方案3】:

您只想调用外部 URL 并使用结果?如果我们谈论的是对服务 JSON 的东西的简单 GET 请求,PHP 开箱即用:

$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);

如果你想做一个发布请求,它会有点困难,但是有很多例子可以用 curl 做到这一点。

所以我想问题是;你到底想要什么?

【讨论】:

  • 我希望能够使用 REST API 的各种功能。所以是的,我需要 POST。我认为(希望......)Laravel 会有一些方法以 Laravel 的方式来做这件事,但我会坚持使用 PHP。谢谢。
  • 如果您不需要结果,只需尝试 HIT API 或 PING URL,这是最好的方法。谢谢:)
【解决方案4】:

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

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 调用的最简单方法。

【讨论】:

    【解决方案5】:

    2019 年 3 月 21 日更新

    使用composer require guzzlehttp/guzzle:~6.3.3添加GuzzleHttp

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

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

    在您调用 API 的类的顶部包含以下行

    use GuzzleHttp\Client;
    

    添加以下代码以发出请求

    $client = new Client();
    
    $res = $client->request('POST', 'http://www.exmple.com/mydetails', [
        'form_params' => [
            'name' => 'george',
        ]
    ]);
    
    if ($res->getStatusCode() == 200) { // 200 OK
        $response_data = $res->getBody()->getContents();
    }
    

    【讨论】:

      【解决方案6】:

      毫无疑问,对于任何 PHP 项目,您可能希望使用 GuzzleHTTP 来发送请求。 Guzzle 有非常好的文档,您可以查看here。 我只想说,您可能希望在 Laravel 项目的任何组件(例如特征)中集中使用 Guzzle 的 Client 类,而不是在 Laravel 的多个控制器和组件上创建 Client 实例(如许多文章和回复建议)。

      我创建了一个你可以尝试使用的 trait,它允许你从 Laravel 项目的任何组件发送请求,只需使用它并调用 makeRequest

      namespace App\Traits;
      use GuzzleHttp\Client;
      trait ConsumesExternalServices
      {
          /**
           * Send a request to any service
           * @return string
           */
          public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
          {
              $client = new Client([
                  'base_uri' => $this->baseUri,
              ]);
      
              $bodyType = 'form_params';
      
              if ($hasFile) {
                  $bodyType = 'multipart';
                  $multipart = [];
      
                  foreach ($formParams as $name => $contents) {
                      $multipart[] = [
                          'name' => $name,
                          'contents' => $contents
                      ];
                  }
              }
      
              $response = $client->request($method, $requestUrl, [
                  'query' => $queryParams,
                  $bodyType => $hasFile ? $multipart : $formParams,
                  'headers' => $headers,
              ]);
      
              $response = $response->getBody()->getContents();
      
              return $response;
          }
      }
      

      请注意,此 trait 甚至可以处理文件发送。

      如果您想了解有关此 trait 的更多详细信息以及将此 trait 集成到 Laravel 的其他内容,请查看article。另外,如果对这个话题感兴趣或者需要大的帮助,可以通过my course全程指导。

      希望对大家有帮助。

      最好的祝愿:)

      【讨论】:

        【解决方案7】:

        Laravel 8 的基本解决方案是

        use Illuminate\Support\Facades\Http;
        
        $response = Http::get('http://example.com');
        

        “GuzzleHTTP 发送请求”和“Illuminate\Http\Request;”之间存在冲突不要问我为什么... [这里是可搜索的]

        所以寻找我在 Laravel 8 Doc 中找到的 1sec...

        **Guzzle 在 Laravel 8 Http 请求中!**

        https://laravel.com/docs/8.x/http-client#making-requests

        如你所见

        https://laravel.com/docs/8.x/http-client#introduction

        Laravel 围绕 Guzzle HTTP 提供了一个富有表现力的最小 API 客户端,允许您快速发出传出 HTTP 请求到 与其他 Web 应用程序通信。 Laravel 的包装 Guzzle 专注于其最常见的用例和精彩的 开发者体验。

        它对我很有用,玩得开心,如果有帮助,请指出!

        【讨论】:

          【解决方案8】:

          你可以使用 Httpful :

          网址:http://phphttpclient.com/

          Github:https://github.com/nategood/httpful

          【讨论】:

          • 看起来不错,虽然它实际上并没有回答我关于 Laravel 的问题,但我一定会调查一下。谢谢!
          • Laravel 还没有开箱即用,但是 Laravel 在 composer 下运行,所以你可以使用像 Httpful 这样的库来完成工作。顺便说一句,您也可以使用requests.ryanmccue.info
          • Laravel 在 composer 之下,所以任何包都是公平的游戏。
          【解决方案9】:

          我还创建了类似于 @JuanDMeGon 的 trait,你可以在项目的任何地方使用它。请检查一下

          trait ApiRequests
          {
            
              public function get($url, $data = null)
              {
                  try {
                      $response = Http::get($this->base_url . $url, $data);
                  } catch (\Exception $e) {
                      info($e->getMessage());
                      abort(503);
                  }
          
                  if ( $response->status() == 401) {
                      throw new AuthenticationException();
                  } else if (! $response->successful()) {
                     abort(503);
                  }
          
                  return $response->json();
              }
          
              public function post($url, $data = [])
              {
                  $token = session()->get('token');
                  try {
                      $response = Http::acceptJson()->withToken($token)->post($this->base_url . $url, $data);
                  } catch (\Exception $e) {
                      abort(503);
                  }
          
                  if ($response->status() == 401 && !request()->routeIs('login')) {
                      throw new AuthenticationException();
                  }
          
                  return $response;
              }
           
          }
          
          
          
          
          
          
          
          class Controller extends BaseController
          {
              protected $base_url;
           
              use AuthorizesRequests, DispatchesJobs, ValidatesRequests, ApiRequests;
          
              public function __construct()
              {
                  $this->base_url = env("BASE_URL","http://192.168.xxxxxxx");
                  
                  View::share('base_url', $this->base_url);
                 
              }
          
          
             
          }
          

          【讨论】:

            猜你喜欢
            • 2022-10-06
            • 1970-01-01
            • 1970-01-01
            • 2019-07-07
            • 2020-05-11
            • 1970-01-01
            • 2021-07-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多