postman PHP从端点返回“null”

htrmnn0y  于 2023-11-18  发布在  Postman
关注(0)|答案(1)|浏览(124)

朋友们,我有返回端点https://api.bcb.gov.br/dados/serie/bcdata.sgs.4390/dados的PHP返回的问题。
在POSTMAN中,它工作正常,浏览器也正常。
问题出在哪里?

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.bcb.gov.br/dados/serie/bcdata.sgs.4390/dados",
  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(
    "Authorization: Basic YXRoZW5hc3g6QHRoZW5hc1g=",
    "Cookie: cookie_p=!scLarubhqjnExZBkmDwhOLi4iPSDyREMccf7/KajFSUEMTzB5Ayusi5+tGpJHXS2/gAiOR1B3EXRVmA=; TS01799025=0198c2d644c9f142b44ab6191be6416ca09c966281b4eac2e338095e981a329beb85787a3328474ab13c2f09d86baa6627e734caa34ceb49d8e51f2f880c249de254c0daa1"
  ),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

字符串
Thanx

hi3rlvi2

hi3rlvi21#

从 Postman 和浏览器,它是工作,因为你是通过https安全连接加载代码和文件。如果你在http或localhost上这样做,你必须添加CURLOPT_SSL_VERIFYPEER => falseCURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'来模拟浏览器并获取结果。但是使用CURLOPT_SSL_VERIFYPEER => false并不真正聪明,让你不安全,更多关于该选项和其他curl选项,你可以在这里阅读https://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTSSLVERIFYPEER
下面是我在localhost上测试的代码,

$curl = curl_init();
curl_setopt_array($curl, array(
   CURLOPT_URL => "https://api.bcb.gov.br/dados/serie/bcdata.sgs.4390/dados",
   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(
      "Authorization: Basic YXRoZW5hc3g6QHRoZW5hc1g=",
      "Cookie: cookie_p=!scLarubhqjnExZBkmDwhOLi4iPSDyREMccf7/KajFSUEMTzB5Ayusi5+tGpJHXS2/gAiOR1B3EXRVmA=; TS01799025=0198c2d644c9f142b44ab6191be6416ca09c966281b4eac2e338095e981a329beb85787a3328474ab13c2f09d86baa6627e734caa34ceb49d8e51f2f880c249de254c0daa1"
   ),
   // those 2 lines added
   CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)',
   CURLOPT_SSL_VERIFYPEER => false,
));
$response = curl_exec($curl);
curl_close($curl);

// decode response 
$obj = json_decode($response);
// output result
var_dump($obj);

字符串

相关问题