Guzzle 6 - 获得有效网址

时间:2017-03-24 19:38:11

标签: object guzzle guzzle6 psr-7 guzzlehttp

我刚从guzzle 3升级到guzzle 6

现在我有一些代码..

$request = $this->_client->get($url);
           $response = $request->send();
           $url = $response->getInfo('url');

           return $url;

更新到guzzle 6后,我看到了getInfo()&由于某种原因,geteffectiveurl()已被删除..所以我的新代码是......

$res = $this->_client->request('GET', $url, ['on_stats' => function (TransferStats $stats) use (&$url) {
                $url = $stats->getEffectiveUri();
                }])->getBody()->getContents();

                return $url;

现在$ url变量是一个GuzzleHttp \ Psr7 \ Uri对象,它并没有真正解决我的问题,因为我只需要将url作为字符串返回。

我如何隐藏对象 - >

[24-Mar-2017 19:12:26 UTC] GuzzleHttp\Psr7\Uri Object
(
    [scheme:GuzzleHttp\Psr7\Uri:private] => https
    [userInfo:GuzzleHttp\Psr7\Uri:private] => 
    [host:GuzzleHttp\Psr7\Uri:private] => signup.testapp.com
    [port:GuzzleHttp\Psr7\Uri:private] => 
    [path:GuzzleHttp\Psr7\Uri:private] => /login
    [query:GuzzleHttp\Psr7\Uri:private] => username=jeff&blablablablabla
    [fragment:GuzzleHttp\Psr7\Uri:private] => 
)

进入一个简单的字符串,我可以传递给另一个请求?

或者我错过了什么? Guzzle 3中的getInfo('url')是解决问题的完美解决方案,肯定是另一个问题取而代之?

由于

1 个答案:

答案 0 :(得分:2)

\GuzzleHttp\Psr7\Uri有一个神奇的__toString() method,它会将URI作为字符串返回给您。

如果您只是想将另一个请求发送到完全相同的URI the docs state

  

创建请求时,您可以将URI作为字符串或Psr \ Http \ Message \ UriInterface的实例提供。

这意味着您可以使用您拥有的$url对象执行对同一URI的第二次请求。

// Your existing code
// I assume this is within a method since it returns $url
$res = $this->_client->request('GET', $url, [
    'on_stats' => function (TransferStats $stats) use (&$url) {
        $url = $stats->getEffectiveUri();
    }
])->getBody()->getContents();

return $url;


// Make a second request to the same URI
// This would be in another method or something after receiving the $url from the above method
$response2 = $this->_client->request('GET', $url);