【问题标题】:Guzzle 6 - getting the effective urlGuzzle 6 - 获取有效的 url
【发布时间】:2017-03-25 08:56:53
【问题描述】:

我刚从 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') 是解决问题的完美解决方案,肯定是另一个问题已取代它的位置吗?

谢谢

【问题讨论】:

    标签: object guzzle6 psr-7 guzzle


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回复,我使用 GuzzleHttp\TransferStats 找到了一种解决方法,并使用了一些方法来查找最后一个 URL,但这有点冗长,所以我会尝试您建议的答案,谢谢!
    猜你喜欢
    • 2016-03-02
    • 2018-10-22
    • 2015-12-09
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    相关资源
    最近更新 更多