尊敬的专家!
我向一项服务的 api 提出请求。如果 api 已经掉线并且服务器不可用,那么 $ch 中将没有任何内容,尽管在正常的 api 操作期间,例如,如果输入了不正确的凭据,则会出现代码错误。如果 api 在技术上不可用(500 错误)或由于其他原因不返回任何内容,如何在 curl 请求期间获取带有响应状态的标头。尝试添加 curl_setopt($ch, CURLOPT_HEADER, 1); 但是请求因此停止工作,并且不仅返回http标头,还返回成功请求的结果(没有这个我得到一个json结构)。也试过
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); print_r($httpcode);
这次代码来了,但与 api 本身的 json 结构相同。假设其中的代码为 0 - 请求成功,那么 $httpcode 将是相同的...我怀疑如果 api 不可用,那里将什么都没有...请告诉我如何仍然获取 http - curl 请求时响应中带有错误状态的标头?
$data = array("user_name" => $this->log, "user_pass" => $this->pass);
$ch = curl_init("$url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLINFO_HTTP_CODE, true);
return json_decode(curl_exec($ch));
在 curl 中,您可以通过 headers 获取信息: