1

我正在尝试使用 cURL PHP 从响应标头中获取响应代码。

当我发送请求时,这是 MYOB AccountRight API 返回的响应标头:

HTTP/1.1 200 OK
Access-Control-Expose-Headers: Request-Context
Cache-Control: must-revalidate, private
Content-Encoding: gzip
Content-Type: application/json;charset=utf-8
Date: Thu, 20 May 2021 01:07:56 GMT
ETag: "XXXXXXXXX"
Expires: -1
Request-Context: appId=cid-v1:a4936349-ef26-4f8a-9268-XXXXXXXXX
Server: Microsoft-IIS/10.0
Vary: Accept-Encoding
X-AspNet-Version: 4.0.30319
X-Mashery-Message-ID: 2fc6b494-54e8-43e2-8bc4-XXXXXXXXX
X-Mashery-Responder: prod-j-worker-ap-southeast-2b-33.mashery.com
x-myobapi-elapsed: 1370
x-myobapi-requestid: bb0764c8-f62d-4848-bcae-XXXXXXXXX
X-Powered-By: ASP.NET
Content-Length: 1205
Connection: keep-alive

我已经尝试了使用 curl 在 PHP 中获取 HTTP 代码的解决方案,但我不会得到 http 代码。

这是我获取帐户数据的代码:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://ar1.api.myob.com/accountright/766d620e-a5eb-41c3-8343-XXXXXXXX/GeneralLedger/Account?$filter=Name%20eq%20\'Inventory\'%20or%20Name%20eq%20\'Cost%20Of%20Sales\'%20or%20Name%20eq%20\'Inventory%20Income\'',
  CURLOPT_HEADER => true,
  CURLOPT_NOBODY => true,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'x-myobapi-version: v2',
    'Accept-Encoding: gzip,deflate',
    'x-myobapi-key: '.$theAPIKey,
    'x-myobapi-cftoken: '.$theCFToken,
    'Authorization: Bearer '.$theAccessToken
  )
));

$response = curl_exec($curl);
$theInfo = curl_getinfo($response);
$http_code = $theInfo['http_code'];
curl_close($curl);
echo 'http code: ' . $http_code . '<br />';
echo '<pre>';
echo $response;
echo '</pre>';

当我回显 http 代码时,不会打印任何内容。

4

1 回答 1

1

我认为你需要传递$curlcurl_getinfo方法,而不是$response

$response = curl_exec($curl);
$theInfo = curl_getinfo($curl);
$http_code = $theInfo['http_code'];

你可以在这里看到文档。https://www.php.net/manual/en/function.curl-getinfo.php

于 2021-05-20T01:36:44.470 回答