1. 程式人生 > >個人寫的http介面測試頁面,支援post和get引數提交

個人寫的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="重新輸入" onclick="location.href='./jiekou.php'"><input type="button" value="返回" onclick="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);
}
?>