新建一个SpringBoot项目,且启动正常
关于如何新建一个SpringBoot项目,可参考这儿。
定义接口
- 接口用于GET请求
//TestInterfaceA.java
package com.jepcc.demo.config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestInterfaceA {
@GetMapping("/test/a")
public String testA(){
return "Hello World!";
}
}
启动应用,打开浏览器输入localhost:8080/test/a
,显示Hello World!
,接口正常。
- 接口用于POST请求
//TestInterfaceB.java
package com.jepcc.demo.config;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestInterfaceB {
@PostMapping("/test/b")
public String testB(String name){
return "Hello,"+name;
}
}
使用IDEA自带的Http Client测试接口
- 在项目根目录下新建目录
http
,在http
目录下新建文件test.http
(注意哈,文件后缀一定要是.http
)
- 定义GET请求,用于访问
/test/a
接口
GET http://localhost:8080/test/a
Accept: application/json
###
- 定义POST请求,用于访问
/test/b
接口
POST http://localhost:8080/test/b
Content-Type: application/x-www-form-urlencoded
name=Nicholas
###
- 执行接口调用
接口单元测试
针对接口/test/a
,编写单元测试代码。
GET http://localhost:8080/test/a
#Accept: application/json
> {%
client.test("test-a",function(){
client.log("Testing Interface:/test/a");
client.log(response.body);
client.assert(response.status===200,"response status is not 200");
client.assert(response.body==="Hello World!","response body is not \"Hello World!\"");
})
%}
###
需要注意的是,记得 “空一行,空一格”。
接口调用历史记录
- Tools>Http Client>Show Http Requests History,可查看Http请求历史记录
- 应用根目录下的
.idea
>httpRequests
中也保存着Http请求历史记录