IntelliJ IDEA Http client使用手册

878 阅读1分钟

参考: www.jetbrains.com/help/idea/h…

一直都是使用postman等工具作为联调接口时发起http请求的工具,但是每次都要单独postman,软件费切换很是麻烦,于是就开始使用IDEA自带的http工具Http client。下面是使用过程中一些常用的功能总结。基本能涵盖百分之九十的场景,如果还有别的需求可以自行去上述参考链接查阅。

基本使用

同级目录下创建http文件和http-client.env.json文件 http-client.env.json示例

{  
  "arm": {  
    "host": "112.31.184.93:42443",  
    "username": "admin",  
    "password": "Password@_"  
  }  
}

.http文件示例

### 获取token  
POST https://{{host}}/v1.0/api/tokens  
Content-type: application/json  
Host: {{host}}  
  
{  
  "username": "{{username}}",  "password": "{{password}}"
} 

后置脚本

前置脚本和后置脚本都支持JavaScript ES6,具体支持的所有API详见: www.jetbrains.com/help/idea/j…

### 获取token  
POST https://{{host}}/v1.0/api/tokens  
Content-type: application/json  
Host: {{host}}  
  
{  
  "username": "{{username}}",  "password": "{{password}}"
}  
  
> {%  
    // 后置脚本,将token设置到环境变量中 提供给后续接口注入
    const body = response.body;  
    const bodyString = JSON.parse(JSON.stringify(body))  
    const token = bodyString.data;  
  
    console.log("token: " + token)  
  
    client.global.set("token", token)  
%}  
  
### 查询itsg设备  
GET https://{{host}}/v1.0/api/devices?pageIndex=1&pageSize=10&name=s0001ln  
Content-Type: application/json  
X-ACCESS-TOKEN: {{token}}

前置脚本

示例1

### 设置参数
< {% request.variables.set("firstname", "John") %}

GET http://example.org/{{firstname}}

示例2

< {%
    const signature = crypto.hmac.sha256()
        .withTextSecret(request.environment.get("secret"))
        .updateWithText(request.body.tryGetSubstituted())
        .digest().toHex();
    request.variables.set("signature", signature)

    const hash = crypto.sha256()
        .updateWithText(request.body.tryGetSubstituted())
        .digest().toHex();
    request.variables.set("hash", hash)
%}

POST https://httpbin.org/post
X-My-Signature: {{signature}}
X-My-Hash: {{hash}}
Content-Type: application/json

{
"prop": "value"
}