【发布时间】:2020-01-02 13:21:51
【问题描述】:
我使用 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 标头不存在。
当我从我收到的终端发出 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 标头?
更新:
通过禁用 Guzzle 重定向仍然存在同样的问题:
$response = $client->request('GET', $downloadUrl, ['allow_redirects' => false]);
通过设置 track_redirects 和 on_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) ""
【问题讨论】:
-
“就像 Location 标头不存在” - 那是因为它不存在。默认情况下,Guzzle 会自动遵循重定向 - 您正在查看的标头是导致后续请求的标头,而不是原始请求的标头。 guzzle3.readthedocs.io/http-client/http-redirects.html
-
我使用 GuzzleHttp 6,我尝试禁用重定向,或者在发生重定向但未执行回调时执行回调
-
然后尝试设置
track_redirects,然后检查标题X-Guzzle-Redirect-History和X-Guzzle-Redirect-Status-History的内容。 -
@misorude 我更新了问题...仍然没有
-
您检查过实际响应是什么吗?也许您通过 Guzzle 发出的请求会得到与您使用 cURL 发出请求时看到的不同 响应(由于某些重要的请求特征在某种程度上有所不同) - 所以可能只是您正在寻找重定向一开始就没有发生……?