ChatGPT解决这个技术问题 Extra ChatGPT

从 Laravel 向外部 API 发出 HTTP 请求

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

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

请帮帮我?

如果仍然感兴趣,您也可以使用 Curl,我猜您可能会说 curl 是 PHP 的 jquery ajax 以某种形式。
您可以使用 Laravel's HTTP Client

C
Community

基于此处对类似问题的回答: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 WAS 将您引导至官方 Laravel 包。它预装在 laravel 供应商组中。
我得到一个 Stream 对象而不是 json 字符串。有人能帮我吗?
我做同样的事情,但我的浏览器无限转动
Laravel 7.x 现在有一种更简单的方法:stackoverflow.com/a/60908329/2341298
K
Kenny Horna

我们可以在 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,因为返回的值是一个整数。
B
Bram

您只想调用外部 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,这是最好的方法。谢谢 :)
S
Syclone

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


这很棒!我正在使用 laravel 9x,效果很好。谢谢!
T
Tiago Martins Peres

更新于 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();
}

J
JuanDMeGon

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

我创建了一个您可以尝试使用的特征,它允许您从 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,它会在整个过程中为您提供指导。

希望对大家有所帮助。

最好的祝愿 :)


S
Sergio Bentes

Laravel 8 的基本解决方案是

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

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

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

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 的封装专注于其最常见的用例和出色的开发人员体验。

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


J
Jeremie Ges

您可以使用 Httpful :

网站:http://phphttpclient.com/

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


看起来很棒,虽然它实际上并没有回答我关于 Laravel 的问题,但我一定会调查一下。谢谢!
Laravel 还没有开箱即用,但是 Laravel 在 composer 下运行,所以你可以使用像 Httpful 这样的库来完成工作。顺便说一句,您也可以使用 requests.ryanmccue.info
Laravel 在作曲家下,所以任何包都是公平的游戏。
5
5 revs, 3 users 65%

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

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);
       
    }
}