이번에는 API 인터페이스를 로컬에서 테스트하는 방법과 API 인터페이스를 로컬에서 테스트할 때 Notes가 무엇인지 보여드리겠습니다. 다음은 실제 사례입니다.
최근에 API 인터페이스를 작성하고 있는데, 인터페이스를 작성할 때마다 먼저 문법적 오류가 있는지, 요청한 데이터가 맞는지 직접 테스트해야 하는데 대부분 POST 요청입니다. , 브라우저에서 링크를 직접 열 수 없습니다. 테스트하려면 데이터 요청을 시뮬레이션하기 위해 로컬로 HTTP 요청을 보낼 수 있는 시뮬레이션 도구가 있어야 합니다.
처음에는 이렇게 했습니다. 로컬 wampserver의 실행 디렉터리에 파일을 만들고 그 안에 Curl 요청을 작성하고 시뮬레이션된 요청 테스트를 수행했습니다. 그러나 각 인터페이스에는 서로 다른 매개변수가 필요했습니다. 계속해야 합니다. 요청 매개변수와 API를 수동으로 수정하는 것은 매우 불편합니다. 나중에 요청 파일에 지저분한 데이터를 구분할 수 없었습니다.

인터넷에서 관련 도구를 검색했는데 ATOOLOnline tools, Apizza 등과 같은 온라인 테스트가 많이 있습니다. , 확인해 보니 모두 잘 작동하고 사용하기 매우 쉽고 인터페이스가 아름답고 서비스가 매우 사려 깊습니다. 하지만 저는 보안 문제를 고려하고 있으며 동시에 데이터를 원본 JSON 형식으로 반환합니다. 이 형식은 더 직관적인 배열 형식으로 보곤 했습니다.
그래서 음식과 옷은 스스로 충분히 만든다는 컨셉에 맞게 로컬에서 간단한 API 테스트 페이지를 작성했고, 데이터 제출 후 로컬에서 API 요청 테스트 기능을 구현했습니다. , 결과를 마음대로 변환할 수 있었습니다. 이 작업을 수행하려면 두 개의 파일만 필요합니다. 하나는 데이터를 채우는 post.html 페이지이고, 다른 하나는 post.html 페이지에서 데이터를 수신하고 함수 구현 요청을 처리하는 post.php 파일입니다. .
1. 프런트 엔드 페이지 파일 post.html

은 단순한 페이지이고, 복잡한 레이아웃도 없고, JS 특수 효과도 없으며, 당분간 6개의 매개변수만 작성되었습니다. 일반적으로 충분함, 충분하지 않음 직접 추가할 수 있습니다. 기본적으로 body요청 매개변수가 여기에 전달되며 요청 메서드는 GET 및 POST만 사용합니다.
<html xmlns="http://blog.csdn.net/sinat_35861727?viewmode=contents">
<head>
<meta http-equiv = "Content-Type" content = "text/html;charset = utf8">
<meta name = "description" content = "提交表单">
<title>API接口请求表单</title>
</head>
<style type="text/css">
.key1{
width:100px;
}
.value1{
width:230px;
margin:0 0 0 10px;
}
.main{
margin:0 auto;
width:450px;
height:auto;
background:lightgray;
padding:40px 40px;
}
.refer{
width:100px;
height:24px;
}
.url{
width:350px;
}
</style>
<body>
<p class="main">
<form method="POST" action="post.php" target="_blank">
<p>请求地址:<input class="url" type="text" name="curl" placeholder="API接口地址"></p>
<p>参 数1: <input class="key1" type="text" name="key1" placeholder="参数名">
<input class="value1" type="text" name="value1" placeholder="参数值"></p>
<p>参 数2: <input class="key1" type="text" name="key2" placeholder="参数名">
<input class="value1" type="text" name="value2" placeholder="参数值"></p>
<p>参 数3: <input class="key1" type="text" name="key3" placeholder="参数名">
<input class="value1" type="text" name="value3" placeholder="参数值"></p>
<p>参 数4: <input class="key1" type="text" name="key4" placeholder="参数名">
<input class="value1" type="text" name="value4" placeholder="参数值"></p>
<p>参 数5: <input class="key1" type="text" name="key5" placeholder="参数名">
<input class="value1" type="text" name="value5" placeholder="参数值"></p>
<p>参 数6: <input class="key1" type="text" name="key6" placeholder="参数名">
<input class="value1" type="text" name="value6" placeholder="参数值"></p>
<p>请求方式: <select name="method">
<option value="POST">POST请求</option>
<option value="GET">GET请求</option>
</select></p>
<p style="text-align:center;"><input class="refer" type="submit" value="提交"></p>
</form>
</p>
</body>
</html>
2. 데이터 파일 처리 post.php
post.html 페이지에서 데이터를 받아 요청을 보낸 다음 요청 결과를 모두 전면에서 전달합니다. 끝 페이지에 여전히 헤더 매개변수가 필요한 경우 이 파일에 수동으로 추가할 수 있습니다.
<?php
echo '<title>API接口请求响应</title>';
/**
* 设置网络请求配置
* @param [string] $curl 请求的URL
* @param [bool] true || false 是否https请求
* @param [string] $method 请求方式,默认GET
* @param [array] $header 请求的header参数
* @param [object] $data PUT请求的时候发送的数据对象
* @return [object] 返回请求响应
*/
function ihttp_request($curl,$https=true,$method='GET',$header=array(),$data=null){
// 创建一个新cURL资源
$ch = curl_init();
// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, $curl); //要访问的网站
//curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($https){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
}
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true); //发送 POST 请求
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
// 抓取URL并把它传递给浏览器
$content = curl_exec($ch);
if ($content === false) {
return "网络请求出错: " . curl_error($ch);
exit();
}
//关闭cURL资源,并且释放系统资源
curl_close($ch);
return $content;
}
//检查是否是链接格式
function checkUrl($C_url){
$str="/^http(s?):\/\/(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/";
if (!preg_match($str,$C_url)){
return false;
}else{
return true;
}
}
//检查是不是HTTPS
function check_https($url){
$str="/^https:/";
if (!preg_match($str,$url)){
return false;
}else{
return true;
}
}
if($_SERVER['REQUEST_METHOD'] != 'POST') exit('请求方式错误!');
//发送请求
function curl_query(){
$data = array(
$_POST['key1'] => $_POST['value1'],
$_POST['key2'] => $_POST['value2'],
$_POST['key3'] => $_POST['value3'],
$_POST['key4'] => $_POST['value4'],
$_POST['key5'] => $_POST['value5'],
$_POST['key6'] => $_POST['value6']
);
//数组去空
$data = array_filter($data); //post请求的参数
if(empty($data)) exit('请填写参数');
$url = $_POST['curl']; //API接口
if(!checkUrl($url)) exit('链接格式错误'); //检查连接的格式
$is_https = check_https($url); //是否是HTTPS请求
$method = $_POST['method']; //请求方式(GET POST)
$header = array(); //携带header参数
//$header[] = 'Cache-Control: max-age=0';
//$header[] = 'Connection: keep-alive';
if($method == 'POST'){
$res = ihttp_request($url,$is_https,$method,$header,$data);
print_r(json_decode($res,true));
}else if($method == 'GET'){
$curl = $url.'?'.http_build_query($data); //GET请求参数拼接
$res = ihttp_request($curl,$is_https,$method,$header);
print_r(json_decode($res,true));
}else{
exit('error request method');
}
}
curl_query();
?>
작성이 매우 간단하고 기능이 그다지 포괄적이지 않습니다. 일반적인 상황에서 POST 및 GET 요청은 여전히 만족할 수 있습니다. 필요한 친구는 코드를 다운로드할 수 있습니다. 자신의 필요에 따라 기능을 수정하고 개선하십시오.
이 기사의 사례를 읽은 후 방법을 마스터했다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요!
추천 자료:
ThinkPHP WeChat 결제 구현(jsapi 결제) 프로세스 튜토리얼 상세 설명_php 예시
위 내용은 API 인터페이스를 로컬에서 테스트하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!