PHP curl 返回Connection timed out解决办法

背景

请求业务方B接口时,返回了报错信息
My NOTICE [请求接口失败信息]
请求接口URL:http://xxxx.com/xx/xx
请求接口时间:30.026
请求接口返回状态:200
请求接口错误信息:connect() timed out!
请求接口错误码:28
请求接口发送的参数:Array

判断原因

本地模拟请求,如果是写一个不存在的域名xx.com,会报错

Could not resolve host:

随手写了一个ip地址,报错就成了

Connection timed out after 2000 milliseconds

解决办法

由于无法判断谁来背锅,而且正式环境无法复现。只能采取重试的方法。
简单逻辑如下

<?php
$ch = curl_init();
// curl_setopt ($ch, CURLOPT_URL, 'produc_redis.php.com');
curl_setopt ($ch, CURLOPT_URL, '11.11.11.1');


// I changed UA here
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1');

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_AUTOREFERER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 2);

$html = curl_exec($ch);

var_dump($html,curl_error($ch));

$num=3;
for($i=1;$i<=$num;$i++){
    if(curl_getinfo($ch,CURLINFO_HTTP_CODE)=='0' && $i<=$num){
      echo "retry $i 次".PHP_EOL;
      if($i==3){
          curl_setopt ($ch, CURLOPT_URL, '220.181.57.217');
      }
      $html = curl_exec($ch);
 }
}

var_dump($html);

var_dump(curl_error($ch));

// var_dump(curl_getinfo($ch));

执行结果

bool(false)
string(44) "Connection timed out after 2000 milliseconds"
retry 1 次
retry 2 次
retry 3 次
string(81) "<html>
<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
</html>
"
string(0) ""
[Finished in 6.1s]

鸟哥关于curl的研究

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值