博客地址: http://blog.720ui.com
在日常开发过程中, 我们或多或少都涉及到 API 接口的测试. 例如, 有的小伙伴使用 Chrome 的 Postman 插件, 或者使用火狐的 restclient 等工具. 事实上, 这些工具是测试 API 接口非常有效的方式之一, 笔者之前也一直使用 Postman 完成 API 接口的测试工作. 今天, 笔者推荐另外一个非常好用的小工具, 能够帮助读者快速测试 API 接口. 这个工具就是 IDEA 的 Editor REST Client.
IDEA 的 Editor REST Client 在 IntelliJ IDEA 2017.3 版本就开始支持, 在 2018.1 版本添加了很多的特性. 事实上, 它是 IntelliJ IDEA 的 HTTP Client 插件.
开始工作
首先, 我们可以在任意目录下创建一个 xxx.http 文件., 如图所示.
这里, 三个 ### 进行 HTTP 请求分割. 事实上, 一个文件可以包含多个 HTTP 请求, ### 后面可以添加注释, 案例如下所示.
- ### 用户登录
- POST http://localhost:8088/oauth/token?grant_type=password&username=lgz&password=123456
- Accept : application/json
- Content-Type : application/json;charset=UTF-8
Authorization: Basic client secret
Cache-Control : no-cache
因此, 我们获得的响应内容.
多环境配置
在开发过程中, 我们通常会存在多套环境, 例如开发环境,* 测试环境, 预发环境, 生产环境等. 因此, 如果 Editor REST Client 能够像 Postman 一样做到多环境配置就太棒了. 事实上, Editor REST Client 已经支持了这个特性, 我们只需要创建 rest-client.env.json 文件, 并且配置多环境信息即可.
- {
- "development" : {
- "url" : "http://localhost:8088",
"token" : "Bearer 4d74c7fb-0ef4-45ec-b3ff-902eaa3d116c"
- },
- "test" : {
- "url" : "http://localhost:8089",
"token" : "Bearer 4d74c7fb-0ef4-45ec-b3ff-902eaa3d116c"
- },
- "preproduction" : {
- "url" : "http://activity.720ui.com",
"token" : "Bearer 4d74c7fb-0ef4-45ec-b3ff-902eaa3d116c"
- },
- "product" : {
- "url" : "http://activity.720ui.com",
- "token" : "Bearer 4d74c7fb-0ef4-45ec-b3ff-902eaa3d116c"
- }
- }
此时, 改造之前的 URL, 将 http://localhost:8088 改造成 {{url}} 代替.
POST {{url}}/oauth/token?grant_type=password&username=lgz&password=123456
这里, 我们获得的整体效果.
案例详解
现在, 我们来写一个完整的案例. 具体配置可以参考: REST Client https://marketplace.visualstudio.com/items?itemName=humao.rest-client
- ### 创建用户信息
- POST {{url}}/v1/m/users
- Accept : application/json
- Content-Type : application/json;charset=UTF-8
- Authorization: {{token}}
- {
- "username": "xiaoyue",
- "realname": "小岳",
- "password": "111111",
- "email": "lianggzone@163.com",
- "tel": "18305930000",
- "weixin": "LiangGzone",
- "sex": 1
- }
- ### 修改用户信息
- PUT {{url}}/v1/m/users/723181
- Accept : application/json
- Content-Type : application/json;charset=UTF-8
- Authorization: {{token}}
- CachePATCH-Control : no-cache
- {
- "username": "xiaoyue"
- }
- ### 查询用户信息
- GET {{url}}/v1/c/users/lgz/username
- Accept : application/json
- Content-Type : application/json;charset=UTF-8
- Authorization: {{token}}
- ### 查询用户信息列表
GET {{url}}/v1/c/users?keyword = 梁
- Accept : application/json
- Content-Type : application/json;charset=UTF-8
- Authorization: {{token}}
参考资料
- https://marketplace.visualstudio.com/items?itemName=humao.rest-client
- (完, 转载请注明作者及出处.)
来源: https://juejin.im/post/5aeeefbe6fb9a07ace58c58a