個人寫的http接口測試頁面,支持post和get參數提交

因爲工作交接需要,花了一會寫的一個類似在線接口測試頁面,如果電腦能跑php,就可以直接使用,歡迎指點改進:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>接口測試</title>
</head>
<body>
<h1>接口測試</h1>
<form action="./jiekou.php" method="POST">
	接口地址:<input type="text" size="100" name="url" value="<?php if(!empty($_POST['url'])){echo $_POST['url'];}?>"><br/>
	參數列表:<input type="text" size="100" name="paramter_list" value="<?php if(!empty($_POST['paramter_list'])){echo $_POST['paramter_list'];}?>">參數1:值1 參數2:值2 ... 另:值是數組請用格式[XX,XX]<br/>
	提交方式:<input type="radio" name="type" value="post" <?php if(!empty($_POST['type']) && $_POST['type']=="post"){echo "checked='checked'";}?>>post <input type="radio" name="type" value="get" <?php if(!empty($_POST['type']) && $_POST['type']=="get"){echo "checked='checked'";}?>>get<br/>
	輸出方式:<input type="radio" name="rtype" value="string" <?php if(!empty($_POST['rtype']) && $_POST['rtype']=="string"){echo "checked='checked'";}?>>json字符串 <input type="radio" name="rtype" value="array" <?php if(!empty($_POST['rtype']) && $_POST['rtype']=="array"){echo "checked='checked'";}?>>array<br/>
	<input type="submit"><input type="button" value="重新輸入" οnclick="location.href='./jiekou.php'"><input type="button" value="返回" οnclick="history.go(-1)">
</form>
</body>
</html>
<?php
if(!empty($_POST)){
	echo "<hr><h1>測試結果:</h1>";
	if(empty($_POST['url'])){
		echo "<font color='red'>接口地址不能為空</font>";
		die;
	}
	$url = $_POST['url'];
	$data = array();
	if(!empty($_POST['paramter_list'])){
		$paramter_list = str_replace(':', ':', $_POST['paramter_list']);
		$paramter_list = trim($paramter_list);
		$paramter_arr = explode(' ', $paramter_list);
		foreach ($paramter_arr as $key => $value) {
			$k = explode(':', $value)[0];
			$v = explode(':', $value)[1];
			if(!empty($_POST['type']) && $_POST['type'] == "post" && strpos($v,'[') === 0 && strpos($v,']') == mb_strlen($v)-1){
				$v = trim(trim($v,'['),']');
				$v = str_replace(',', ',', $v);
				$v = explode(',',$v);
			}
			$data[$k] = $v;
		}
		if(!empty($_POST['type']) && $_POST['type'] == "get"){
			$paramter_list = str_replace(':', '=', $paramter_list);
			$paramter_list = str_replace(' ', '&', $paramter_list);
			$url .= strpos($url,'?') ? "&" . $paramter_list : "?" . $paramter_list;
		}
	}
	// curl獲取接口
	$ch =  curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	if(!empty($_POST['type']) && $_POST['type'] == "get"){
		curl_setopt($ch, CURLOPT_HEADER, 0);
	}else{
		// post數據
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的變量
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
	}

	$output = curl_exec($ch);
	curl_close($ch);

	if(!empty($_POST['rtype']) && $_POST['rtype'] == "string"){
		echo $output;die;
	}
	$output = json_decode($output,true);

	//打印獲得的數據
	echo "<pre>";
	print_r($output);
}
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章