记一次php curl导致的故障
本地和alpha环境curl请求第三方接口正常
beta环境curl请求失败
代码如下
public static function getCurl($url, $type = 'get', $data = '', $decode = true, $header = array()) { $ch = curl_init(); // 初始化CURL句柄 curl_setopt($ch, CURLOPT_TIMEOUT, 5);//设置超时3秒钟 curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设为TRUE把curl_exec()结果转化为字串,而不是直接输出 if (strtolower($type) == 'post') { curl_setopt($ch, CURLOPT_POST, 1); //启用POST提交 is_array($data) && $data = http_build_query($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST提交的字符串 } if (!empty($header)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } $document = curl_exec($ch); //执行预定义的CURL $info = curl_getinfo($ch, CURLINFO_HTTP_CODE); //得到返回信息的特性 curl_close($ch); if ($info >= 200 && $info < 300) { if ($decode) { return json_decode($document, true); } return $document; } else { return array("result" => "fail", "cause" => $document); } }
解决方案
强制使用IPV4请求
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl配置说明:
http://php.net/manual/zh/function.curl-setopt.php
curl 命令行进行请求
-4 代表使用IPV4
-d 传递数据,json形式的'{"app_id":"ceshi","secret_key":"123456"}',form形式的"app_id=ceshi&secret_key=123456"
-X POST形式
-H 设置请求头
curl -4 url -X POST -H "Content-Type:application/json" -d '{"app_id":"ceshi","secret_key":"123456"}'
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。