php封装curl的post和get类

<pre name="code" class="php"><?
class curl{
	/**
	 * get方法
	 *
	 * @param string 接口地址
	 * @param string endpoint 
	 * @param string model名
	 * @param string 方法名
	 * @param array 参数
	 * @return json
	 */
    static public function sendByGet($host,$data){
		$fields_string = '';
		if(!empty($data)){
			ksort($data);
			$fuhao = '';
			foreach($data as $k=>$v){
				$fields_string .=$fuhao.$v;
				$fuhao = '/';
			}
		}
        if(!empty($fields_string)){
            $url = $host.'/'.$fields_string;
        } else {
            $url = $host;
        }
		$ch = curl_init() ;
		curl_setopt($ch, CURLOPT_URL,$url) ;
		curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		$str = curl_exec($ch);

        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE );
        curl_close($ch);
   		if ($status == 200) {
			return $str;
		} else {
			return false;
		}
	}
	
    /**
     * post方法
     *
     * @param string 接口地址
     * @param array 参数
     * @return json
     */
	public function sendByPost($url,$data,$cookie=''){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		if($cookie){
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		}
		
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120 );
		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
		$str = curl_exec($ch);
		if (curl_errno($ch)) {
		     $error = "Curl error: " . curl_error($ch)."\n时间:".date('Y-m-d H:i:s',time())."\r\n";
			 file_put_contents('curl_post_error.txt',$error,FILE_APPEND);
		}
		curl_close($ch) ;
		return $str;
	}
}

当获取https协议请求时需加上

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值