基於 springboot+vue 的測試平台開發繼續更新。
添加的接口,我要來調試確定是否是通的,那么要發送接口請求,今天來實現這個功能,先預覽一下:
捋一下思路,分為三步走:
- 點擊發送按鈕,調用后端接口
- 后端接口處理內部,發送http接口請求
- 后端接口把響應返回給前端展示
一、http客戶端選型
為了更方便快捷的開發功能,直接選用 hutool 框架中封裝好的 http客戶端。
官方介紹:Hutool-http 針對JDK 的HttpUrlConnection做一層封裝,簡化了HTTPS請求、文件上傳、Cookie記憶等操作,使Http請求變得無比簡單。
Hutool-http的核心集中在兩個類:
- HttpRequest
- HttpResponse
同時針對大部分情境,封裝了HttpUtil工具類。根據Hutool的“便捷性與靈活性並存”原則,HttpUtil 的存在體現了便捷性,那 HttpRequest對象的使用則體現了靈活性,使用此對象可以自定義更多的屬性給請求,以適應Http請求中的不同場景(例如自定義header、自定義cookie、自定義代理等等)。
看過介紹,我瀏覽了下源代碼,然后測試了一下,發現可以滿足我使用需求。
// get1
@Test
void get1() {
String result1 = HttpUtil.get("http://localhost:8080/bloomtest/user/useInfo?token=admin-token");
System.out.println(result1);
}
// get2
@Test
void get2() {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", 33);
String result2 = HttpRequest.get("http://localhost:8080/bloomtest/apiDefinition/getApi")
.form(paramMap)
.execute()
.body();
System.out.println(result2);
}
比如,發送get請求,HttpUtil 其實是基於 HttpRequest 的進一步分裝,我這里還是直接統一使用 HttpRequest 。
另外,發送 post 請求也很簡單,可以直接傳入 json 字符串:
@Test
void testPost() {
String reqBody = "{\n" +
" \"projectName\": \"項目zzz1\",\n" +
" \"description\": \"測試新增項目\"\n" +
"}";
//鏈式構建請求
String result3 = HttpRequest.post("http://localhost:8080/bloomtest/project/add")
// .header(Header.CONTENT_TYPE, "application/json")//頭信息,多個頭信息多次調用此方法即可
// .timeout(20000)//超時,毫秒
.body(reqBody)
.execute().body();
}
關於http請求的常用信息,請求頭、參數、delete/put 等等其他方法,框架都是支持的,目前我只實現最基本的需求。
二、后端接口實現
測試過了上面的代碼,心里就有數了,在后端接口里就看怎么使用它了。
這個發送請求的接口,目前需要支持如下:
- get、post 方法
- 查詢參數(/list?id=3)、rest參數(/list/3)以及請求 body(json)
header暫時先不加,目前我項目里的接口都不需要傳指定的 header,后期實現了權限之后再對應完善代碼。
1. controller 層
ApiDefinitionController 類中繼續新增處理器方法。
@PostMapping("/apiTestRun")
public Result apiTestRun(@RequestBody ApiRunTestRequest apiRunTestRequest) {
return Result.success(apiDefinitionService.apiTestRun(apiRunTestRequest));
}
2. service 層
對應service層實現,先放出全部代碼,目前還是以初期實現為主,代碼后續可能會進一步優化:
public JSONObject apiTestRun(ApiRunTestRequest request) {
// url 拼接
String url = request.getHost() + request.getPath();
// 判斷不同請求參數類型:0 query參數,1 rest參數, 2使用 body參數
int queryType = request.getRequestType();
if (queryType == 0) {
// query 參數
HashMap<String, Object> paramMap = new HashMap<>();
JSONArray jsonArray = JSONArray.parseArray(request.getRequest());
for (int i=0; i<jsonArray.size(); i++) {
paramMap.put(jsonArray.getJSONObject(i).get("queryKey").toString(), jsonArray.getJSONObject(i).get("value"));
}
if (request.getMethod().equals("get")) {
String result = HttpRequest.get(url)
.form(paramMap)
.execute()
.body();
return JSONObject.parseObject(result);
}
if (request.getMethod().equals("post")) {
String result = HttpRequest.post(url)
.form(paramMap)
.execute()
.body();
return JSONObject.parseObject(result);
}
} else if (queryType == 1) {
// rest參數
HashMap<String, Object> paramMap = new HashMap<>();
JSONArray jsonArray = JSONArray.parseArray(request.getRequest());
for (int i=0; i<jsonArray.size(); i++) {
paramMap.put(jsonArray.getJSONObject(i).get("restKey").toString(), jsonArray.getJSONObject(i).get("value"));
}
// 去掉path后面的參數,還原path
List<String> list = Arrays.asList(request.getPath().split("/\\{"));
String orginPath = list.get(0);
// 解析path中的參數,確認參數拼接順序
List<String> resultFindAll = ReUtil.findAll("(?<=\\{)(.+?)(?=\\})", request.getPath(), 0);
String appendParamPath = "";
for (String i : resultFindAll) {
appendParamPath = appendParamPath.concat("/" + paramMap.get(i));
}
// 發送請求
if (request.getMethod().equals("get")) {
String result = HttpRequest
.get(request.getHost() + orginPath + appendParamPath)
.execute()
.body();
return JSONObject.parseObject(result);
}
if (request.getMethod().equals("post")) {
String result = HttpRequest
.post(request.getHost() + orginPath + appendParamPath)
.execute()
.body();
return JSONObject.parseObject(result);
}
} else if (queryType == 2) {
// 請求體
if (request.getMethod().equals("post")) {
String reqBody = request.getRequest();
String result = HttpRequest.post(url)
.body(reqBody)
.execute().body();
return JSONObject.parseObject(result);
}
// 請求體
if (request.getMethod().equals("get")) {
String reqBody = request.getRequest();
String result = HttpRequest.get(url)
.body(reqBody)
.execute().body();
return JSONObject.parseObject(result);
}
}
return null;
}
乍一看比較多,其實分開看就好:
- 根據參數類型,分別對於 query、rest、body 的請求參數情況進行處理
- 在其中每種類型里,又區分了 get、post 方法
簡單介紹下其中各種的要點。
(1)query 參數
主要是前面的 2 步:
- 拿到前端的入參,解析成 JSONArray,內部元素類型又是 JSONObject
- 遍歷 JSONArray,通過
jsonArray.getJSONObject(i)
方法獲取各 JSONObject 的 key,對應前端入參的queryKey
和value
,就是參數名和參數值。 - 接着發送請求,拿到的返回是一個 String,解析成 JSONObject 返回給 controller
(2)rest 參數
處理 rest 參數稍微麻煩了些,比如:localhost:8080/bloomtest/module/list/3
,最后的3
才是參數。
處理過程就像我注視寫的:
- 獲取前端傳來的參數
首先跟上面一樣,獲取到前端的參數名和值,放到 HashMap 里,熟悉 python的童鞋就當作放到字典里了。
- 解析path中的參數,確認參數拼接順序
因為參數名需要跟 url 里的拼接的值順序對應上才行,接口里保存的url是這樣的:/bloomtest/module/list/{projectId}
,大括號里的就是參數。
所以這里使用了正則去匹配我要的內容,表達式(?<=\{)(.+?)(?=\})
我搜的,具體我也不熟悉,后續再學習。
ReUtil.findAll
方法也是來自於 hutool 框架,可以查找到所有符合表達式的內容,返回是一個數組。
然后遍歷這個數組,把里面的參數逐個拼接到一個空字符串里appendParamPath
:
String appendParamPath = "";
for (String i : resultFindAll) {
appendParamPath = appendParamPath.concat("/" + paramMap.get(i));
}
- 去掉path后面的參數,還原path
因為前端傳過來的 path 是/bloomtest/module/list/{projectId}
,需要去掉最后的/{projectId}
才可以使用。
List<String> list = Arrays.asList(request.getPath().split("/\\{"));
String orginPath = list.get(0);
使用了字符串分割split
方法,返回的是一個String[]
數組,又通過Arrays.asList
進一步做了轉化,就可以使用get(0)
獲取第一個使用了,也就是/bloomtest/module/list
。
前面都齊了,就可以發送請求了,注意最終請求的 url 還是要拼接一下:request.getHost() + orginPath + appendParamPath
(3)請求體
這個最簡單,前端傳過來的 json 字符串直接傳入即可:
if (request.getMethod().equals("post")) {
String reqBody = request.getRequest();
String result = HttpRequest.post(url)
.body(reqBody)
.execute().body();
return JSONObject.parseObject(result);
}
要注意的是,這里用的 JSONObject 是來自fastjson
,之前用 hutool 帶的處理,會有報錯,搞了好一會。
三、前端實現
我這里是整個功能開發完成后進行整理的,實際上,后端接口邏輯不是一次性寫完的。先寫好一個可以前端調得通的接口,然后一點點前后調試完成。
前端這里做的事情不多,在【發送】按鈕上綁定一個點擊實踐,調用后端開發好的接口。
方法apiTestRun
內部,主要是處理請求入參,調用請求,處理返回即可:
紅框里是調用接口的部分,前面的是處理入參。這里的 3 個判斷是看目前點擊了哪個 tab,然后傳對應入參類型給接口。
接下來測試下功能OK。
四、修改遺留 bug
在測試功能的時候,發現了幾個問題。大概表現都是因為前端參數賦值,或者沒重置干凈導致的。
增加和修改了一些代碼,具體不貼了,需要最新代碼的可以聯系我,直接發給你參考。