0
点赞
收藏
分享

微信扫一扫

记录一个比较完善的php的curl请求方法的demo

有点d伤 2023-09-11 阅读 46

function httpRequest($url, $dataStr = "", $isPost = 0,$headers=[])
{
    $httpInfo = [];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // 请求头
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    // 跳过证书检查
    if (strtolower(mb_substr($url,0,8,"utf-8")) == "https://") {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
    }

    if ($isPost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataStr);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        curl_setopt($ch, CURLOPT_URL, $url . "?" . $dataStr);
    }
    //echo $url."?".$dataStr;
    $response = curl_exec($ch);
    if ($response === false) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}



$url = "http://v.juhe.cn/calendar/day";
$params = [
    "key" => "您申请的AppKey",
    "date" => "2015-1-1",
    
];

$paramsStr = http_build_query($params);//get请求需要转换,post可以直接用数组
$headers = ["Content-Type" => "application/x-www-form-urlencoded"];

$content = httpRequest($url, $paramsStr,0,$headers);
$result = json_decode($content, true);
if ($result) {
    var_dump($result);
    // 具体返回示例值,参考返回参数说明、json返回示例
} else {
    // 请求异常
}

举报

相关推荐

0 条评论