响应处理示例
在本主题中,我们将查看几个 HTTP 响应处理示例。 若要亲自尝试这些示例,请浏览 auth-requests 和 test-responses requests collections。
检查响应头、正文和内容类型
在本示例中,我们将创建若干测试以验证以下内容:
要创建测试,我们调用 test 方法,该方法属于 client 对象。 在测试中,您可以通过调用 assert 方法,该方法属于 client 对象,并引用 response 对象的各项属性来进行验证。
### Check response status, headers, and content-type
GET https://httpbin.org/get
> {%
client.test("Request executed successfully", function() {
client.assert(response.status === 200, "Response status is not 200");
});
client.test("Headers option exists", function() {
client.assert(response.body.hasOwnProperty("headers"), "Cannot find 'headers' option in response");
});
client.test("Response content-type is json", function() {
var type = response.contentType.mimeType;
client.assert(type === "application/json", "Expected 'application/json' but received '" + type + "'");
});
%}
使用全局变量
在此示例中,我们将从接收到的响应中提取一个值到 global variable 中,以便在后续请求中使用。
第一个请求包含一个响应处理脚本,该脚本会从收到的响应正文中提取身份验证令牌,并将其保存到 auth_token 变量中的 client.global 下。 为实现此目的,我们使用 client.global.set(VariableName, VariableValue) 构造。 作为 VariableValue 参数,我们使用了服务器返回的 response body 中 token 字段的值。 该值随后被赋给 "auth_token" 变量。
POST https://examples.http-client.intellij.net/body-echo
Content-Type: application/json
{
"token": "my-secret-token"
}
> {% client.global.set("auth_token", response.body.token); %}
请求执行完毕后,可在后续请求(通过 {{auth_token}} 变量)和响应处理脚本(借助 client.global.get("auth_token") 构造)中访问 auth_token 变量。
//Accessing a variable
GET https://examples.http-client.intellij.net/headers
Authorization: Bearer {{auth_token}}
要从响应头中获取值,请使用 valueOf 方法,该方法属于 headers 对象。 如果收到多个具有相同名称的头(例如 Set-Cookie ),请改用 valuesOf 方法。 这将返回所有响应头值的数组。
POST https://httpbin.org/cookies
//Saving a cookie from the first Set-Cookie header
> {%
client.global.set("my_cookie", response.headers.valuesOf("Set-Cookie")[0]);
%}
处理事件流的每一行
如果订阅事件流,当有新数据可用时,服务器将自动向客户端发送事件。 此类数据可以是服务器发送事件或以换行符分隔的 JSON(NDJSON)格式。 在 WebStorm 中,您可以使用 HTTP Client 的 response.body.onEachLine 方法来为该事件流的每一行调用一个函数。
假设您有一台服务器,定期发送关于黄金价格的信息。 在此示例中,我们将编写一个响应处理脚本,执行以下操作:
获取从服务器收到的每一块数据(JSON 对象),并记录价格值。 运行请求后,您可以在 响应处理程序 标签页的 服务 工具窗口中查看日志信息。
当事件数量超过 10 个时,停止处理接收到的数据。 请注意,这不会将您从事件流中取消订阅——只要 HTTP 连接处于开启状态,您仍将继续接收事件(请查看 控制台 标签页的 服务 工具窗口)。
测试获取的数据块:如果价格小于 45,测试将失败。 您可以在 测试 标签页中的 服务 工具窗口中查看测试结果。
GET localhost/stocks/subscribe?symbol=GOLD
> {%
var updatesCount = 0;
response.body.onEachLine(
(symbolUpdate, unsubscribe) => {
updatesCount++;
client.log(symbolUpdate.pricePresentation);
if (updatesCount > 10) {
unsubscribe();
return;
}
client.test("Price test " + updatesCount, () => {
client.assert(symbolUpdate.lastPrice >= 45, "Price must be >= 45");
client.log(symbolUpdate.pricePresentation);
});
}
)
%}
最后修改日期: 2025年 9月 26日