如何使用Curl检查API请求超时?

时间:2016-05-03 06:15:24

标签: php api curl timeout connection-timeout

我有一个场景。在这里,我使用Curl访问API。 如果无法访问API,我必须发送提醒电子邮件。那么如果有请求超时,我怎么检查?

这是我的代码。

    $alerthttp1 = array();
    $string = 'somestring';
    $key = md5($string);
    $service_url = 'www.someurl.com/'.$key;

    $curl = curl_init($service_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 300);
    $curl_response = curl_exec($curl);
    $curl_errno = curl_errno($curl);
    $curl_error = curl_error($curl);

    error_log(json_encode($curl_errno));
    error_log(json_encode($curl_error));

    if(curl_error($curl) || $curl_response === false || $curl_errno > 0)
    {
        $info = curl_getinfo($curl);
        hlog_errorlog('error occured during curl exec - ' . var_export($info));
        hlog_errorlog('error -----------> '. $curl_error); 
        curl_close($curl);

        $alerthttp1[] = array('status' => 'FAILED');//for email alert
    }

请建议我,最好的编码方式。

谢谢

2 个答案:

答案 0 :(得分:2)

尝试使用CURLOPT_CONNECTTIMEOUT而不是CURLOPT_TIMEOUT CURLOPT_CONNECTTIMEOUT是允许与服务器建立连接的最长时间(以秒为单位)。

答案 1 :(得分:0)

不,你不能用CURL知道它。询问API支持。或者自己选择超时时间。通常是30秒。