源码
注: 缓存预热和缓存刷新返回数据的格式是相同的,参考测试示例中缓存预热的代码
<?php
function sendRequestJSON($url, $method = 'GET', $postData = null, $headers = null, $timeout = 10) {
$ch = curl_init();
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($postData)) {
$postData = json_encode($postData);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
if (!empty($headers)) {
$formattedHeaders = [];
foreach ($headers as $key => $value) {
$formattedHeaders[] = $key . ': ' . $value;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $formattedHeaders);
} else {
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$response = curl_exec($ch);
if ($response === false) {
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $response;
}
// 缓存预热
function prefetch_cache($token,$urlList,$type){
$url = "https://cdn.api.baishan.com/v2/cache/prefetch?token=" . $token;
$postData = array(
"urls" => $urlList,
"type" => $type,
);
return sendRequestJSON($url,"POST",$postData);
}
// 缓存刷新
function refresh_cache($token,$urlList,$type){
$url = "https://cdn.api.baishan.com/v2/cache/refresh?token=" . $token;
$postData = array(
"urls" => $urlList,
"type" => $type,
);
return sendRequestJSON($url,"POST",$postData);
}
// 测试示例
$res = prefetch_cache("这是Token",["第一个URL","第二个URL"],"url");
// $res = prefetch_cache("这是Token",["第一个目录","第二个目录"],"dir");
$resDe = json_decode($res,true);
if($resDe["code"] == 0){
echo("任务id: " . $resDe["data"]["task_id"]);
echo("<br>");
echo("成功提交链接数: " . $resDe["data"]["count"]);
echo("<br>");
if(!empty($resDe["data"]["err_urls"])){
echo("失败链接列表: " . json_encode($resDe["data"]["err_urls"]));
echo("<br>");
}
}else{
echo("错误码: " . $resDe["code"]);
echo("<br>");
echo("错误信息: " . $resDe["message"]);
}