[PHP]代码
- /**
- * http request processing class (encapsulated based on CURL)
- *
- * @author Xiwei Ye
- * @version $Id$
- */
- class cls_http_request
- {
-
- /**
- * Get method request (curl)
- *
- * @param string $url requested url
- * @param integer $timeout timeout (s)
- * @return string (request successful) | false (request failed)
- */
- public static function curl_get($url, $timeout = 1)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- $result = curl_exec($ch);
- curl_close($ch);
- if (is_string($result) && strlen($result))
- {
- return $result;
- }
- else
- {
- return false;
- }
- }
-
- /**
- * Post request
- *
- * @param string $url The requested url
- * @param array $data The requested parameter array (associative array)
- * @param integer $timeout Timeout time (s)
- * @return string( Request successful) | false (request failed)
- */
- public static function curl_post($url, $data, $timeout = 2)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- $result = curl_exec($ch);
- curl_close($ch);
- if (is_string($result) && strlen($result))
- {
- return $result;
- }
- else
- {
- return false;
- }
- }
-
- /**
- * Multiple url parallel requests
- *
- * @param array $urls url array
- * @param integer $timeout timeout time (s)
- * @return array $res return result
- */
- public static function curl_get_urls($urls, $timeout = 1)
- {
- $mh=curl_multi_init();
- $chs=array();
- foreach($urls as $url)
- {
- $ch=curl_init();
- curl_setopt($ch,CURLOPT_URL,$url);
- curl_setopt($ch,CURLOPT_HEADER,false);
- curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
- curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
- curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);
- curl_multi_add_handle($mh,$ch);
- $chs[]=$ch;
- }
- $active=null;
- do {
- $mrc=curl_multi_exec($mh,$active);
- }while($mrc == CURLM_CALL_MULTI_PERFORM);
- while($active && $mrc == CURLM_OK)
- {
- if(curl_multi_select($mh) != -1)
- {
- do{
- $mrc=curl_multi_exec($mh,$active);
- }while($mrc == CURLM_CALL_MULTI_PERFORM);
- }
- }
- $res=array();
- foreach($chs as $ch)
- {
- $res[]=curl_multi_getcontent($ch);
- curl_multi_remove_handle($mh,$ch);
- }
- curl_multi_close($mh);
- return $res;
- }
- }
复制代码
|