【问题标题】:URI from Response on GuzzleHttp来自 GuzzleHttp 上的响应的 URI
【发布时间】:2020-11-27 17:17:12
【问题描述】:

我需要从GuzzleHTTPResponse 中获取URI,目前正在使用getAsync,并同时处理至少50 个项目,需要一种方法来获取URI我从大嘴里使用Client

$groups->each(function($group) {
    $promises = $group->map( function($lead, $index) {
        $client = new Client(['http_errors' => false]);
        return $client->getAsync($lead->website, [
            'timeout' => 5, // Response timeout
            'connect_timeout' => 5, // Connection timeout
        ]); 
    })->toArray();
    settle($promises)->then( function($results) {
        $collections = collect($results);
        $fulfilled = $collections->where('state', 'fulfilled')->all();
    })->wait();
});

似乎Request 有这个getUri 方法,但Response 没有也无法在接口或类和文档中找到。希望有人能提供帮助

编辑:尝试getEffectiveUrl,但这仅适用于 Guzzle 5,目前使用 6

【问题讨论】:

    标签: php laravel guzzle


    【解决方案1】:

    这是为 guzzle 5 准备的

    在响应中,您没有 getUri 方法,因为只有请求具有此方法。

    如果发生重定向或发生某些事情,您可以使用以下方法获取响应 url

    $response = GuzzleHttp\get('http://httpbin.org/get');
    echo $response->getEffectiveUrl();
    // http://httpbin.org/get
    
    $response = GuzzleHttp\get('http://httpbin.org/redirect-to?url=http://www.google.com');
    echo $response->getEffectiveUrl();
    // http://www.google.com
    

    https://docs.guzzlephp.org/en/5.3/http-messages.html#effective-url

    Guzzle 6

    来自docs 的 Guzzle 6.1 解决方案。

    use GuzzleHttp\Client;
    use GuzzleHttp\TransferStats;
    
    $client = new Client;
    
    $client->get('http://some.site.com', [
        'query'   => ['get' => 'params'],
        'on_stats' => function (TransferStats $stats) use (&$url) {
            $url = $stats->getEffectiveUri();
        }
    ])->getBody()->getContents();
    
    echo $url; // http://some.site.com?get=params
    

    学分

    https://stackoverflow.com/a/35443523/8193279

    【讨论】:

    • 嘿,谢谢你的回答。,请看编辑的行.. 目前使用 Guzzle 6
    • 这对 Guzzle 5 很有帮助。*
    猜你喜欢
    • 2014-10-08
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多