Laravel - Guzzle 请求/cURL 错误 6:无法解析主机

Laravel - Guzzle Request / cURL error 6: Could not resolve host

我尝试向 Github API 发出 API 请求,只是为了测试。我在 Laravel 5.1 APP 上安装了最新的 Guzzle 版本 ( "guzzle/guzzle": "^3.9" )。 在我的 routes.php 中,我有以下代码:

Route::get('guzzle/{username}', function($username) {
    $client = new Client([
        'base_uri' => 'https://api.github.com/users/',
    ]);
    $response = $client->get("/users/$username");
    dd($response);
});

如果我现在访问 URL 域。dev/github/kayyyy 我收到错误 cURL error 6: Could not resolve host: users

为什么我会收到这个错误?

如果我访问 https://api.github.com/users/kayyyy,我可以看到 json 输出。

我也在用Homestead / Vagrant 是不是楼主无法解决的问题?

编辑 如果我在没有 base_uri 的情况下尝试这样做。

Route::get('guzzle/{username}', function($username) {
   $client = new GuzzleHttp\Client();
    $response = $client->get("https://api.github.com/users/$username");
    dd($response);
});

实际上在单引号内不可能进行变量插值。这意味着您当前正在调用 users/$username 并且 $username 变量未被其值替换。

为了获得它,您应该通过以下方式之一使用它:

$response = $client->get("users/$username")->send();
$response = $client->get('users/' . $username)->send();

我个人更喜欢第二个,因为它被认为更快。

你为什么打电话给 $client->get->()->send()?特别是,为什么要在最后链接 send() 方法?在演示看似相同的操作时,文档没有附加 send() 方法:

http://guzzle.readthedocs.org/en/latest/quickstart.html#creating-a-client

此外,您是否考虑过上面引用的手册页上此声明的含义?

When a relative URI is provided to a client, the client will combine the base URI with the relative URI using the rules described in RFC 3986, section 2.

好的,我解决了,我的愚蠢错误。 我用了new Client

当然应该是new GuzzleHttp\Client

因为它只是为了在我的 routes.php 中进行测试,所以我没有 Namespace

感谢大家的帮助。

感谢 Paratron https://github.com/googleapis/google-api-php-client/issues/1184#issuecomment-355295789 就我而言,在 cakephp 3.8 和 docker 19.03.5 上,由于某些网络问题,我遇到了 curl 错误。我重新启动了我的 cake-server docker 容器,它运行得非常棒。