我正在使用中间件来跟踪重定向链中的请求并保存最后一个。最后一个请求的 uri 就是你想要的。
试试这个代码:
$stack = \GuzzleHttp\HandlerStack::create();
$lastRequest = null;
$stack->push(\GuzzleHttp\Middleware::mapRequest(function (\Psr\Http\Message\RequestInterface $request) use(&$lastRequest) {
$lastRequest = $request;
return $request;
}));
$client = new Client([
'handler' => $stack,
\GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true
]);
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org/redirect-to?url=http://stackoverflow.com');
$response = $client->send($request);
var_dump($lastRequest->getUri()->__toString());
结果:
string(24) "http://stackoverflow.com"
类示例:
class EffectiveUrlMiddleware
{
/**
* @var \Psr\Http\Message\RequestInterface
*/
private $lastRequest;
/**
* @param \Psr\Http\Message\RequestInterface $request
*
* @return \Psr\Http\Message\RequestInterface
*/
public function __invoke(\Psr\Http\Message\RequestInterface $request)
{
$this->lastRequest = $request;
return $request;
}
/**
* @return \Psr\Http\Message\RequestInterface
*/
public function getLastRequest()
{
return $this->lastRequest;
}
}
$stack = \GuzzleHttp\HandlerStack::create();
$effectiveYrlMiddleware = new EffectiveUrlMiddleware();
$stack->push(\GuzzleHttp\Middleware::mapRequest($effectiveYrlMiddleware));
$client = new Client([
'handler' => $stack,
\GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true
]);
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org/redirect-to?url=http://stackoverflow.com');
$response = $client->send($request);
var_dump($effectiveYrlMiddleware->getLastRequest()->getUri()->__toString());