【发布时间】:2019-07-06 13:12:19
【问题描述】:
我正在尝试使用以下代码在 php 中使用 curl 发出 GET 请求。
test.php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://apiaddress/collection',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer 374dad6fdc005a0f17c49aeg77rbifuy48t7205hfhf7he8857c'
),
CURLINFO_HEADER_OUT => true
));
$response = curl_exec($curl);
$err = curl_error($curl);
$info = curl_getinfo($curl, CURLINFO_HEADER_OUT);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "Response code: " . $httpCode . "\nResponse body: \n" . $response . "\n";
}
curl_close($curl);
echo $info;
此请求在 Postman 中有效,并使用此 curl 命令 curl -X GET \
https://apiaddress/collection -H 'Authorization: Bearer 374dad6fdc005a0f17c49aeg77rbifuy48t7205hfhf7he8857c' 有效,但是当我在 cli 中运行 php test.php 时,我得到此输出。我猜我缺少标头或在某处发送了不正确的标头?
响应码:401
响应正文:
{"type":"https://apiaddress/errors#error-unauthorized","title":"Unauthorized","detail":"No 提供的授权凭证。您必须提供授权 此请求的令牌。","status":401}
GET /collection HTTP/2
主机:apiaddress
接受:*/*
授权:承载 374dad6fdc005a0f17c49aeg77rbifuy48t7205hfhf7he8857c
【问题讨论】:
-
$info包含什么? -
$info是上面以 GET 开头的输出 -
我也怀疑这是标题的问题,为什么不比较两者呢?您可能需要在 PHP 请求中指定
Content-Type。