1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 模拟HTTP请求超时时间设置

模拟HTTP请求超时时间设置

时间:2024-08-21 00:48: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 optionscurl_setopt($ch, CURLOPT_URL, "/");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 browsercurl_exec($ch);// close cURL resource, and free up system resourcescurl_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("", 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);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。