我在节点js中有一个API,当出现问题时会返回错误消息,但是当我想在PHP中使用“ file_get_contents”显示它时,它将返回“ null”。何时应该:
{" errMsg ":" Do not found information! "," Status ": 400}
http://repuveconsulta.com:3001/api/plateinfos/1?plate_number=xx&captcha_code=y78
$placa = $_POST['search_field'];
$codigo = $_POST['code'];
$id =$_POST['id'];
$response = file_get_contents('http://repuveconsulta.com:3001/api/plateinfos/'.$id.'?plate_number='.$placa.'&captcha_code='.$codigo);
var_dump($response);
var_dump($Array2 = json_decode($response, true));
答案 0 :(得分:1)
我认为您会得到null,因为您的状态为400,我在本地主机上对其进行了测试,并得到以下响应:
Warning: file_get_contents(http://repuveconsulta.com:3001/api/plateinfos/1?plate_number=xx&captcha_code=y78): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\wamp64\www\****\controllers\Home.php on line 46
C:\ wamp64 \ www *** \ controllers \ Home.php:47:null
也许您可以使用curl来检查响应代码,但我不知道file_get_contents是否可行:
$url = 'http://repuveconsulta.com:3001/api/plateinfos/1?plate_number=xx&captcha_code=y78';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump(json_decode($result, true));
var_dump($status_code);
您还可以添加:
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // The maximum number of seconds to allow cURL functions to execute.
针对curl请求,因此当您的服务中断时,网站将一直挂起,直到出现超时错误为止