PHP GuzzleHttp 获取响应位置 header

PHP GuzzleHttp get response Location header

我使用 GuzzleHttp 6:

发出 GET 请求
use GuzzleHttp\Client as GuzzleClient;
$client = new GuzzleClient([
  'headers' => [
    'Authorization'=>'Bearer XXXX'
  ],        
]);
$downloadUrl = "XXX";
$response = $client->request('GET', $downloadUrl);

$headers = $response->getHeaders();
var_dump($headers['Location']);
var_dump($response->getHeader('Location'));

这些 var_dump 打印空数组,如 Location header 不存在。

当我从终端发出 curl 请求时,收到的响应是:

< HTTP/1.1 302 Found
< Cache-Control: private
< Transfer-Encoding: chunked
< Content-Type: text/plain
< Location: https://xxxx.xxx/yyy/zzz
< request-id: 57388d31-2acf-47b7-80e0-d5a30bcf7f5c
< client-request-id: XXXXX
< x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Europe","Slice":"SliceC","Ring":"3","ScaleUnit":"003","RoleInstance":"AGSFE_IN_9","ADSiteName":"NEU"}}
< Duration: 175.4042
< Strict-Transport-Security: max-age=31536000
< Date: Thu, 29 Aug 2019 09:28:14 GMT
< 
* Connection #0 to host graph.microsoft.com left intact

我应该怎么做才能获得 Location header?

更新:

通过禁用 Guzzle 重定向,仍然存在同样的问题:

$response = $client->request('GET', $downloadUrl, ['allow_redirects' => false]);

通过设置 track_redirectson_redirect 回调没有任何反应:

$onRedirect = function(RequestInterface $request, ResponseInterface $response, UriInterface $uri){
    echo 'Redirecting! ' . $request->getUri() . ' to ' . $uri . "\n";
};

$response = $client->request('GET', $downloadUrl, [
    'allow_redirects' => [
        'max'             => 10,        // allow at most 10 redirects.
        'strict'          => true,      // use "strict" RFC compliant redirects.
        'referer'         => true,      // add a Referer header
        'protocols'       => ['http', 'https'], // only allow https URLs
        'on_redirect'     => $onRedirect,
        'track_redirects' => true
    ]
]);

var_dump($response->getHeaderLine('X-Guzzle-Redirect-Status-History'));
var_dump($response->getHeaderLine('X-Guzzle-Redirect-History'));
var_dump($response->getHeaderLine('Location'));

打印出来:

string(0) ""
string(0) ""
string(0) ""

您应该将 Guzzle 处理程序更改为 Curl。

首先你应该确保你的系统中安装了php-curl

如果您没有安装 php-curl,安装后检查您是否仍然没有收到 Location header。

如果问题仍然存在,您可以尝试:

use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;

$handler = new CurlHandler();
$stack = HandlerStack::create($handler); // Wrap w/ middleware

$client = new GuzzleClient([
    'headers' => $headers,
    'handler'=> $stack
]);