简单封装curl的get与post发送数据

简介:
<?php
header('content-type:text/html;charset=utf-8');

class Curl{
    private $ch;
    private $curl_url;
    function __construct($url=null){
        $this->ch = curl_init();
        $this->curl_url = $url;

    }

    /**post和get方式发送数据
     * @param $method string post或get方式
     * @param $vars 数据
     */
    function sendData( $vars = array(), $method = 'get',$url = ''){
        if($method != 'post' && $method != 'get'){
            exit('请输入有效的提交方式post或get');
            return false;
        }

        if(!empty($url)){
           $this->curl_url = $url;
            return false;
        }else if(empty($this->curl_url)){
            exit('url不能为空');
            return false;
        }

        if($method == 'post'){
            curl_setopt($this->ch, CURLOPT_POST, 1);
            curl_setopt($this->ch, CURLOPT_URL,$this->curl_url);
            if(is_array($vars) && !empty($vars)) {
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $vars);
            }
        }
        else if($method == 'get'){
            if(is_array($vars) && !empty($vars)) {
                $query = http_build_query($vars);
                curl_setopt($this->ch, CURLOPT_URL,$this->curl_url.'?'.$query);//将数组转化为字符串参数
            }else{
                curl_setopt($this->ch, CURLOPT_URL,$this->curl_url);//传递进来的url后可能有参数
            }
        }
        //执行命令
        $data = curl_exec($this->ch);
        //关闭URL请求
        curl_close($this->ch);
        return $data;
    }
}

$ch = new Curl('http://localhost/index.php');
$res = $ch->sendData(array('num'=>12), 'post');




目录
相关文章
|
12月前
|
缓存
POST 为什么会发送两次请求?
POST 为什么会发送两次请求?
794 0
|
14天前
|
JSON 安全 前端开发
post为什么会发送两次请求?
post为什么会发送两次请求?
59 12
|
4月前
|
Web App开发 Shell 开发者
使用 curl 发送请求
cURL 是一个通过 URL 传输数据的,功能强大的命令行工具。cURL 可以与 Chrome Devtool 工具配合使用,把浏览器发送的真实请求还原出来,附带认证信息,脱离浏览器执行,方便开发者重放请求、修改参数调试,编写脚本。也可以单独使用,根据自己的需求构造请求调整参数,构造多种接口测试场景。
42 1
|
4月前
|
JSON API 数据安全/隐私保护
CURL 发送POST请求
CURL 发送POST请求
|
4月前
|
XML 安全 前端开发
post为什么会发送两次请求详解
【6月更文挑战第5天】在Web开发中,开发者可能会遇到POST请求被发送了两次的情况,
122 0
|
5月前
|
Web App开发 JSON 网络安全
CURL发送POST请求
CURL发送POST请求
257 0
|
5月前
restTemplate 发送http post请求带有文件流、参数
restTemplate 发送http post请求带有文件流、参数
139 1
|
JSON 数据格式
QT 给http服务器发送GET/POST请求并接收返回值
QT 给http服务器发送GET/POST请求并接收返回值
QT 给http服务器发送GET/POST请求并接收返回值
|
移动开发 C++ Windows
纯C++实现的HTTP请求封装(POST/GET)
纯C++实现的HTTP请求(POST/GET),支持windows和linux, 进行简单的封装, 方便调用。实现如下: #include "HttpConnect.h" #ifdef WIN32 #pragma comment(lib,"ws2_32.
10104 1