首页 > 解决方案 > 如何使用 Symfony HttpClient 获取所有中间重定向

问题描述

如何使用 HttpClient 获取所有重定向的 url?

这是一个例子:

  1. http://example.com/page 301 重定向到:
  2. http://www.example.com/page 302 重定向到:
  3. http://www.example.com/page/
$response = $this->httpClient->request('GET', 'http://example.com/page');
$content = $response->getContent(false);    
$ary = $response->getInfo();

只有在 getInfo 的 '[debug]' 部分我可以看到:

Issue another request to this URL: 'http://www.example.com/page'
...
Issue another request to this URL: 'http://www.example.com/page/'

有没有办法在不解析调试文本的情况下检索重定向的 URL?

标签: symfony

解决方案


您可以通过设置 max_redirects 参数来拦截重定向:

try {
    $this->httpClient->request('GET', 'http://example.com/page', ['max_redirects' => 0])->getContent();
    // not redirected
} catch (RedirectionException $e) {
    $redirectUrl = $e->getResponse()->getInfo()['redirect_url'];
}

推荐阅读