响应处理示例
在本主题中,我们将研究几个 HTTP 响应处理示例。 如需亲自尝试示例,请探索 auth-requests 和 test-responses requests collections。
检查响应头、主体和内容类型
在此示例中,我们将创建多个测试以验证以下内容:
创建测试时,我们调用 test 方法 客户端 对象。 在测试中,我们可以通过调用 client 对象的 assert 方法来断言特定条件,并引用 回应对象的各种属性以进行验证。
### 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 参数,我们使用从服务器返回的 响应主体 中 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 变量可以从后续请求(在 {{auth_token}} 变量中)和响应处理程序脚本(通过 client.global.get("auth_token") 结构)中访问。
//Accessing a variable
GET https://examples.http-client.intellij.net/headers
Authorization: Bearer {{auth_token}}
要从响应头中获取一个值,请使用 valueOf 方法的 标头 对象。 如果收到多个具有相同名称的头(这在 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)。 在 RubyMine 中,您可以使用 HTTP 客户端 response.body.onEachLine 方法对此事件流的每一行调用一个函数。
假设您有一台定期发送黄金价格信息的服务器。 在这个示例中,编写一个响应处理程序脚本,执行以下操作:
将从服务器接收到的每个数据块(JSON 对象)记录并记录价格值。 当您运行请求时,您可以在 响应处理程序 选项卡中的 服务 工具窗口查看记录的信息。
当事件数量超过 10 时停止处理接收到的数据。 请注意,这不会取消您对事件流的订阅——只要 HTTP 连接保持开放,您将继续接收事件(检查 Console 选项卡的 服务 工具窗口)。
测试获取的数据块:如果价格低于 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日