PHP GUZLE HTTP获取响应位置头
我用GuzzleHttp 6发出了一个PHP GUZLE HTTP获取响应位置头,php,curl,guzzle,guzzle6,guzzlehttp,Php,Curl,Guzzle,Guzzle6,Guzzlehttp,我用GuzzleHttp 6发出了一个GET请求: use GuzzleHttp\Client as GuzzleClient; $client = new GuzzleClient([ 'headers' => [ 'Authorization'=>'Bearer XXXX' ], ]); $downloadUrl = "XXX"; $response = $client->request('GET', $downloadUrl); $hea
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'));
这些变量转储打印空数组,如位置
标头不存在
当我用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
通过设置track\u redirects
和on\u redirect
callback,不会发生任何情况:
$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 handler更改为Curl 首先,您应该确保系统中安装了
php curl
。
如果没有安装php curl
,请在安装后检查是否仍然没有收到位置
标题
如果问题仍然存在,您可以尝试:
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
$handler = new CurlHandler();
$stack = HandlerStack::create($handler); // Wrap w/ middleware
$client = new GuzzleClient([
'headers' => $headers,
'handler'=> $stack
]);
“就像位置标头不存在一样”-这是因为它不存在。默认情况下,Guzzle会自动跟踪重定向,您查看的标题是导致重定向的后续请求的标题,而不是原始标题。我使用HTTP 6,我尝试禁用重定向,或者在发生重定向而未执行回调时执行回调,然后尝试设置
track\u重定向
,然后检查标题X-Guzzle-Redirect-History
和X-Guzzle-Redirect-Status-History
的内容。@misorude我更新了问题。。。还是没有你检查过实际的反应是什么吗?也许您通过Guzzle发出的请求得到的响应与您使用cURL发出请求时看到的不同(由于某些重要的请求特征在某种程度上有所不同),因此可能只是您正在寻找一开始没有发生的重定向…?
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
$handler = new CurlHandler();
$stack = HandlerStack::create($handler); // Wrap w/ middleware
$client = new GuzzleClient([
'headers' => $headers,
'handler'=> $stack
]);