我的cURL请求为何失败?API身份验证返回空结果排查
cURL调用API返回空结果,提示“Could not resolve host”的问题排查与解决
问题背景
使用PHP cURL调用身份验证API时,curl_exec()返回空结果,排查cURL错误后得到提示:Could not resolve host: api.hp.upm.edu.my。相关代码如下:
验证类代码
<?php class General{ #to verify user password with api public static function verifyUser($user,$pswd){ #url $url = 'https://api.hp.upm.edu.my/cron/request/verify.php'; # initiate cur $ch = curl_init($url); # create json data $jsonData = array( 'jtoken' => "test123", 'id' => "$user", 'pass'=> "$pswd" ); #Encode the array into JSON. $jsonDataEncoded = json_encode($jsonData); #Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); #Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); #Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); #Execute the request $result = curl_exec($ch); curl_close($ch); return $result; } } ?>
调用代码
$result = General::verifyUser($_POST['user'], $_POST['pass']); $obj = json_decode($result, true);
问题原因
Could not resolve host本质是DNS解析失败——你的运行环境(本地电脑/服务器)无法将域名api.hp.upm.edu.my转换成对应的IP地址,导致无法和API服务器建立网络连接,最终curl_exec()返回空。
解决步骤
先验证域名是否可正常解析
在终端执行nslookup api.hp.upm.edu.my或ping api.hp.upm.edu.my,如果返回“无法找到主机”类提示,确认是DNS解析问题。调整DNS配置
- 本地开发环境:修改电脑的DNS服务器设置,换成公共DNS(比如谷歌8.8.8.8、国内114.114.114.114)
- 线上服务器:Linux系统修改
/etc/resolv.conf添加可靠DNS;Windows服务器在网络适配器设置里调整DNS地址
确认API域名有效性
直接用浏览器或Postman访问https://api.hp.upm.edu.my/cron/request/verify.php,如果也无法访问,说明该域名可能已失效或被防火墙拦截,需要联系API提供者确认。优化cURL错误处理(建议添加)
在代码中增加错误捕获逻辑,方便后续快速排查问题:#Execute the request $result = curl_exec($ch); // 新增错误检查 if(curl_errno($ch)){ $error = curl_error($ch); curl_close($ch); throw new Exception("CURL请求失败: {$error}"); } curl_close($ch); return $result;
内容的提问来源于stack exchange,提问作者Mesmerised95
相关产品推荐
相关产品推荐

