Laravel 5.4 和 HTTP_Request2

Laravel 5.4 and HTTP_Request2

所以我已经在我的 laravel 项目上安装了 pear/http_request2,但似乎无法正常工作。我正在尝试的是 Bing 图片搜索 API:

的以下代码
    $request = new \Http_Request2('https://api.cognitive.microsoft.com/bing/v5.0/images/search');
    $url = $request->getUrl();

    $headers = array(
        // Request headers
        'Content-Type' => 'multipart/form-data',
        'Ocp-Apim-Subscription-Key' => '{subscription key}',
    );

    $request->setHeader($headers);

    $parameters = array(
        'q' => 'query string',
    );

    $url->setQueryVariables($parameters);

    $request->setMethod(HTTP_Request2::METHOD_POST);

    $request->setBody("{body}");

    try
    {
        $response = $request->send();
        $response->getBody();
    } catch (HttpException $ex) {
        $ex;
    }

每当我在我的控制器上调用它时,我都会收到 "Class 'Http_Request2' not found" 错误。我如何才能在我的项目中使用 pear/http_request2?

更新:解决方案

我发现我可以使用 base_path 来使用非 Laravel 包。

我加了

require_once $path = base_path('vendor/pear/http_request2/HTTP/Request2.php');

现在可以使用了。

如果我查看此处提供的 HTTP_Request2 的最终用户文档:http://pear.php.net/manual/en/package.http.http-request2.intro.php,我可以看到一个示例用例,其代码开头如下:

<?php
require_once 'HTTP/Request2.php';

$request = new HTTP_Request2('http://pear.php.net/', HTTP_Request2::METHOD_GET);

您可以先尝试使用行 "require_once 'HTTP/Request2.php';" 包含 HTTP_Request2,然后创建新的 HTTP_Request2 实例。

问题是 Laravel 使用 Composer 包提供的 PSR-4 自动加载,但 HTTP_Request2 不能那样工作。但是,在您的代码中使用 require_once() 应该可以在 Laravel 中正常工作而不会出现问题。只需确保使用 Request2.php 文件的正确路径即可。