封装的 sendRequest()
函数是一个通用的发送请求函数,可以发送 POST、GET、PUT、DELETE 请求。下面对该函数的代码进行具体讲解:
"multipart/form-data",2=>"application/json",3=>"application/x-www-form-urlencoded"];
$contentType=$contentTypeArr[$contentType];
}
// 创建一个 cURL 资源
$curl = curl_init($url);
// 判断是否为 HTTPS 请求
if (stripos($url, "https://") !== false) {
// 设置 SSL 选项
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 不验证证书
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 不验证主机名
curl_setopt($curl, CURLOPT_SSLVERSION, 1); // 使用 TLSv1 协议
}
// 根据请求方法设置 cURL 选项
switch ($method) {
case 'POST':
curl_setopt($curl, CURLOPT_POST, true);
break;
case 'GET':
curl_setopt($curl, CURLOPT_HTTPGET, true);
break;
case 'PUT':
$contentType = 'application/json';
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'DELETE':
$contentType = 'application/json';
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}
// 设置 cURL 选项
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
// 设置请求头
$headers[] = 'Content-Type: ' . $contentType;
if (!empty($headers)) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
// 根据编码格式设置请求参数
if ($data !== null) {
if ($contentType == 'application/json') {
$postData = json_encode($data);
} elseif ($contentType == 'multipart/form-data') {
$postData = $data;
} elseif ($contentType == 'application/x-www-form-urlencoded') {
$postData = http_build_query($data);
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
}
// 发送请求并获取响应
$response = curl_exec($curl);
// 检查是否有错误发生
if ($response === false) {
$error = curl_error($curl);
// 处理错误信息
} else {
// 处理响应数据
}
// 关闭 cURL 资源
curl_close($curl);
// 返回响应数据
return $response;
}
$data = array(
'field1' => 'value1',
'field2' => 'value2'
);
$headers = array(
'Authorization: Bearer token'
);
$url='xxx.com/test.php';
$response = sendRequest('POST', $url, $data, 1, $headers, 60);
var_dump($response);
接收方式
var_dump($_POST);
$url='xxx.com/test.php?a=1';
$response = sendRequest('GET', $url);
var_dump($response);
接收方式
var_dump($_GET);
$data = array(
'field1' => 'value1',
'field2' => 'value2'
);
$url='xxx.com/test.php';
$response = sendRequest('PUT', $url, $data);
接收方式
var_dump(json_decode(file_get_contents('php://input'),true));
$data = array(
'field1' => 'value1',
'field2' => 'value2'
);
$url='xxx.com/test.php';
$response = sendRequest('DELETE', $url, $data);
接收方式
var_dump(json_decode(file_get_contents('php://input'),true));