模拟HTTP请求超时时间设置

时间:2023-03-09 21:40:13
模拟HTTP请求超时时间设置

HTTP请求有两个超时时间:一个是连接超时时间,另一个是数据传输的最大允许时间(请求资源超时时间)。

使用curl命令行

连接超时时间用 --connect-timeout 参数来指定
数据传输的最大允许时间用 -m 参数来指定
例如:
curl --connect-timeout 10 -m 20 "http://XXXXXXX"
连接超时的话,出错提示形如:
curl: (28) connect() timed out!
数据传输的最大允许时间超时的话,出错提示形如:
curl: (28) Operation timed out after 2000 milliseconds with 0 bytes received

使用PHP的curl_init

连接超时时间
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
数据传输的最大允许时间
curl_setopt($ch, CURLOPT_TIMEOUT, 3); 
使用curl_error($ch)查看错误的详情
<?php

// create a new cURL resource
$ch = curl_init(); // set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// grab URL and pass it to the browser
curl_exec($ch); // close cURL resource, and free up system resources
curl_close($ch); var_dump(curl_error($ch));

使用PHP的fsockopen

连接超时时间
fsockopen( $hostname, $port, $errno, $errstr, $timeout);
数据传输的最大允许时间
暂时不清楚,虽然可以通过stream_set_timeout和stream_get_meta_data(需放在fread之后才有效果)得到是否数据传输超时,但是不能在设置的超时时间内停止请求,所以目标页内容如果sleep请求页会一直停止直到达到最大执行时间。
示例
<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
echo "Unable to open\n";
} else { fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
stream_set_timeout($fp, 2);
$res = fread($fp, 2000); $info = stream_get_meta_data($fp);
fclose($fp); if ($info['timed_out']) {
echo 'Connection timed out!';
} else {
echo $res;
} }
?>

使用file_get_contents

连接超时时间和数据传输的最大允许时间均为设置的timeout,如

<?php
$timeout = 60;
$options = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n",
'timeout' => $timeout
)
);
$context = stream_context_create($options);
$contents = file_get_contents($source, false, $context);
?>

file_get_contents模拟post和get

function http_request($url, $post = null)
{
$timeout=30;
if(is_array($post))
{
  ksort($post);
  $options['http'] = array
  (
  'timeout'=>$timeout,
  'method' => 'POST',
  'content' => http_build_query($post, '', '&'),
  );
}
$context = stream_context_create($options);
return file_get_contents($url, false, $context);
}