A-系統(tǒng):請(qǐng)求頁(yè)面(使用的php請(qǐng)求)
<!-- 這里是獲取調(diào)用數(shù)據(jù) -->
<?php
//連接數(shù)據(jù)庫(kù)
require_once 'get_db_conn.php';
$conn = db_connect();
//提交表單
if (isset($_POST['Save'])) {
//傳入api
$url = 'http://XXX/project/api/external/test.php';
//請(qǐng)求頭
$headers = array(
'Content-Type: application/json',
'AccessKeyId: 1XTAJKZSK02KMSZW47D2LSFQMMUV3LST',
'AccessKeySecret: VS7EGQTB2CGWZXREL3QT3V72ZSRPYSXB'
);
//請(qǐng)求參數(shù)
$json_data = '{
"datainfo": [
{
"require1": "require1_value",
"require2": "require2_value",
"test3": "test_value"
}
]
}';
// 初始化cURL會(huì)話(huà)
$ch = curl_init();
// 設(shè)置cURL選項(xiàng)
// 設(shè)置了請(qǐng)求的目標(biāo)URL
curl_setopt($ch, CURLOPT_URL, $url);
// 發(fā)出一個(gè)POST請(qǐng)求
curl_setopt($ch, CURLOPT_POST, true);
// 設(shè)置HTTP請(qǐng)求頭信息
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// curl_exec()函數(shù)會(huì)將獲取到的數(shù)據(jù)以字符串形式返回,而非直接輸出到瀏覽器或標(biāo)準(zhǔn)輸出。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 設(shè)置POST請(qǐng)求的主體數(shù)據(jù)。這里$json_data是一個(gè)JSON格式的字符串,它會(huì)被作為POST請(qǐng)求的數(shù)據(jù)部分發(fā)送給服務(wù)器。
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
// 在進(jìn)行HTTPS連接時(shí)是否驗(yàn)證服務(wù)器的SSL證書(shū),設(shè)置為false意味著cURL在連接時(shí)將跳過(guò)SSL證書(shū)驗(yàn)證過(guò)程
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 執(zhí)行cURL請(qǐng)求
$response = curl_exec($ch);
// 檢查cURL執(zhí)行是否成功
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
// 處理響應(yīng)數(shù)據(jù)
$result = json_decode($response, true);
// 根據(jù)API返回的數(shù)據(jù)進(jìn)行后續(xù)操作...
echo json_encode($result); // 使用print_r()函數(shù)打印返回的數(shù)據(jù)以便于調(diào)試和查看
}
// 關(guān)閉cURL會(huì)話(huà)
curl_close($ch);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8'); ?>" method="POST" enctype="multipart/form-data">
<div class="centre">
<input type="submit" name="Save" value="提交">
</div>
</form>
</body>
</html>
B-系統(tǒng):被請(qǐng)求頁(yè)面(test.php)
<?php
//連接數(shù)據(jù)庫(kù)
require_once 'get_db_conn.php';
$conn = db_connect();
// 在HTTP響應(yīng)頭中設(shè)置內(nèi)容類(lèi)型(Content-Type)為 application/json。告知客戶(hù)端服務(wù)器即將發(fā)送的數(shù)據(jù)格式是JSON
header('Content-Type: application/json');
// 檢查并驗(yàn)證AccessKeyId和AccessKeySecret(假設(shè)已實(shí)現(xiàn)驗(yàn)證函數(shù))
// 這里僅為示例,實(shí)際應(yīng)根據(jù)您的密鑰管理系統(tǒng)進(jìn)行驗(yàn)證
$access_key_id = isset($_SERVER['HTTP_ACCESSKEYID']) ? $_SERVER['HTTP_ACCESSKEYID'] : '';
$access_key_secret_provided = isset($_SERVER['HTTP_ACCESSKEYSECRET']) ? $_SERVER['HTTP_ACCESSKEYSECRET'] : '';
//調(diào)用方法validate_access_keys判斷密鑰是否正確
if (!validate_access_keys($access_key_id, $access_key_secret_provided)) {
//設(shè)置HTTP響應(yīng)狀態(tài)碼為401,該狀態(tài)碼表示用戶(hù)未經(jīng)過(guò)授權(quán),無(wú)法訪(fǎng)問(wèn)請(qǐng)求的資源。
http_response_code(401);
//返回錯(cuò)誤信息給客戶(hù)端
echo json_encode(['error' => 'Unauthorized']);
// 結(jié)束當(dāng)前腳本的執(zhí)行,不再執(zhí)行后續(xù)的任何代碼。
exit;
}
// 檢查請(qǐng)求方法和Content-Type
// 超全局變量,用于獲取當(dāng)前HTTP請(qǐng)求的方法
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
// 客戶(hù)端請(qǐng)求使用的方法(如GET、POST、PUT等)在服務(wù)器上針對(duì)指定資源不允許使用
http_response_code(405);
//返回錯(cuò)誤信息給客戶(hù)端
echo json_encode(['error' => 'Method Not Allowed']);
// 結(jié)束當(dāng)前腳本的執(zhí)行,不再執(zhí)行后續(xù)的任何代碼。
exit;
}
// 預(yù)定義的服務(wù)器變量,它包含了客戶(hù)端在HTTP請(qǐng)求頭中發(fā)送過(guò)來(lái)的Content-Type值。這個(gè)值描述了請(qǐng)求主體(POST數(shù)據(jù)或PUT數(shù)據(jù)等)的內(nèi)容類(lèi)型
$content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
// 用stripos函數(shù)查找 $content_type 字符串中是否以 'application/json' 開(kāi)頭。stripos 函數(shù)與 strpos 類(lèi)似,但它是不區(qū)分大小寫(xiě)的查找。
if (stripos($content_type, 'application/json') !== 0) {
// 表示服務(wù)器無(wú)法處理請(qǐng)求實(shí)體的媒體類(lèi)型。
http_response_code(415);
//返回錯(cuò)誤信息給客戶(hù)端
echo json_encode(['error' => 'Unsupported Media Type']);
// 結(jié)束當(dāng)前腳本的執(zhí)行,不再執(zhí)行后續(xù)的任何代碼。
exit;
}
// 獲取并解析請(qǐng)求體中的JSON數(shù)據(jù)
// 從特殊的PHP輸入流 'php://input' 中讀取數(shù)據(jù)。這個(gè)輸入流提供了對(duì)HTTP請(qǐng)求正文(請(qǐng)求體)的訪(fǎng)問(wèn),特別適用于POST請(qǐng)求中傳輸?shù)姆潜韱螖?shù)據(jù),例如JSON或XML格式的數(shù)據(jù)
$input_json = file_get_contents('php://input');
// json_decode 函數(shù),該函數(shù)用于將JSON格式的字符串 $input_json 解析成PHP變量。這里的第二個(gè)參數(shù)設(shè)為 true,表示將JSON對(duì)象解碼為PHP關(guān)聯(lián)數(shù)組,而不是默認(rèn)的StdClass對(duì)象
$input_data = json_decode($input_json, true);
// 檢查請(qǐng)求體中是否有必需的參數(shù)(現(xiàn)在考慮嵌套結(jié)構(gòu))
if (!isset($input_data['datainfo'][0]['require1'], $input_data['datainfo'][0]['require2'])) {
// 如果沒(méi)有找到所需的參數(shù),則返回錯(cuò)誤
http_response_code(400);
echo json_encode(['error' => 'Invalid Request Body']);
exit;
}
// 使用請(qǐng)求參數(shù)執(zhí)行業(yè)務(wù)邏輯
$require1 = $input_data['datainfo'][0]['require1'];
$require2 = $input_data['datainfo'][0]['require2'];
// 注意:這里似乎沒(méi)有'test3'在根級(jí)別的數(shù)據(jù)項(xiàng),所以如果'test3'也在'data'數(shù)組內(nèi),則應(yīng)該這么寫(xiě):
$test3 = $input_data['datainfo'][0]['test3'];
//調(diào)用方法查詢(xún)數(shù)據(jù)
$data = fun_select($require1, $require2, $test3, $conn);
// 返回成功響應(yīng)
http_response_code(200);
echo json_encode(['data' => $data,'msg' => 'success','require1'=>$require1]);
/**
* 示例性驗(yàn)證AccessKeyId和AccessKeySecret的方法,實(shí)際項(xiàng)目中應(yīng)實(shí)現(xiàn)自己的驗(yàn)證邏輯
*/
function validate_access_keys($key_id, $key_secret) {
// 實(shí)現(xiàn)驗(yàn)證邏輯,如果驗(yàn)證通過(guò)則返回true,否則返回false
//這里給出默認(rèn)值
if($key_id == '1XTAJKZSK02KMSZW47D2LSFQMMUV3LST' && $key_secret == 'VS7EGQTB2CGWZXREL3QT3V72ZSRPYSXB'){
return true;
}
return false; // 默認(rèn)返回false,僅做占位
}
//執(zhí)行查詢(xún)的方法
function fun_select($require1, $require2, $test3, $conn) {
$sql_select = "SELECT * FROM accountgroups";
$result_select = mysqli_query($conn, $sql_select);
// 檢查查詢(xún)是否成功
if ($result_select) {
// 將查詢(xún)結(jié)果轉(zhuǎn)換為數(shù)組
$data = [];
while ($row = mysqli_fetch_assoc($result_select)) {
$data[] = $row;
}
// 返回查詢(xún)結(jié)果
return $data;
} else {
// 查詢(xún)失敗時(shí)返回錯(cuò)誤信息或者空數(shù)組
echo "SQL查詢(xún)執(zhí)行失敗: " . mysqli_error($conn);
return [];
}
}
?>
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-857041.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-857041.html
到了這里,關(guān)于PHP:接口請(qǐng)求與被請(qǐng)求的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!