响应处理示例
本主题将介绍几个 HTTP 响应处理示例。 要亲自尝试这些示例,请查看 auth-requests 和 test-responses 请求集合。
检查响应头、正文和内容类型
在本示例中,我们将创建多个测试以验证以下内容:
要创建测试,我们调用 client 对象的 test 方法。 在测试内部,我们可以通过调用 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 + "'");
});
%}
使用全局变量
在本示例中,我们将把收到的响应中的某个值捕获到一个 全局变量 中,随后可在后续请求中使用。
第一个请求包含一个响应处理脚本,该脚本会将从收到的响应正文中获取的身份验证令牌保存到 client.global 下的 auth_token 变量中。 为此,我们使用 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}} 变量)和响应处理脚本(通过 client.global.get("auth_token") 构造)中访问 auth_token 变量。
//Accessing a variable
GET https://examples.http-client.intellij.net/headers
Authorization: Bearer {{auth_token}}
要从响应标头获取值,请使用 valueOf 方法(属于 headers 对象)。 如果收到多个同名头部,请改用 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]);
%}
将 Cookie 保存为全局变量
在本示例中,我们将发送一个返回 Cookie 的请求,通过响应处理脚本从响应中提取该 Cookie,将其值保存为 全局变量 ,并在后续请求中复用。
假设某个端点在响应中返回一个 SOCS Cookie。 我们使用 response.cookiesByName("SOCS") 方法从响应中查找并提取此 Cookie。
将 Cookie 值保存为全局变量 (client.global.set()) 后,我们就可以在后续请求中复用它。 在下一个请求中,我们在 Cookie 头部中引用 {{SOCS_COOKIE}} 以发送提取的值。
GET https://www.google.com
> {%
const cookie = response.cookiesByName("SOCS")[0];
if (cookie) {
client.global.set("SOCS_COOKIE", cookie.value);
console.log("Saved SOCS_COOKIE =", cookie.value);
} else {
console.log("SOCS cookie not found");
}
%}
###
// Request 2 — Send the saved cookie to a test endpoint that echoes cookies
GET https://httpbin.org/cookies
Cookie: SOCS={{SOCS_COOKIE}}
逐行处理事件流
如果订阅事件流,当有新数据可用时,服务器会自动向您的客户端发送事件。 这些数据可以采用 Server-Sent Events 或以换行分隔的 JSON(NDJSON)形式。 在 PyCharm 中,您可以使用 HTTP 客户端的 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);
});
}
)
%}
使用 DOM API 处理 XML 响应
如果响应的 Content-Type 为 XML(例如 application/xml 或 text/xml ),HTTP 客户端会将 response.body 以 DOM Document 形式暴露。 要解析和验证响应,可以直接使用 支持的 DOM 方法。 如果需要进行字符串操作或正则表达式处理,可以使用 new XMLSerializer().serializeToString(response.body) 将 DOM Document 序列化为字符串。
XML 响应验证
假设服务器以 XML 格式返回早餐菜单。 在此示例中,响应处理脚本会从 XML 文档中提取值,并通过测试进行验证。
GET https://www.w3schools.com/xml/simple.xml
> {%
client.test("First food item is Belgian Waffles", () => {
const foods = response.body.getElementsByTagName("food");
client.assert(foods.length > 0, "No food elements found");
const firstFood = foods[0];
const name = firstFood
.getElementsByTagName("name")[0]
.textContent
.trim();
const calories = firstFood
.getElementsByTagName("calories")[0]
.textContent
.trim();
client.log("Name:", name);
client.log("Calories:", calories);
client.assert(name === "Belgian Waffles", "Unexpected food name: " + name);
client.assert(calories === "650", "Unexpected calories: " + calories);
});
%}
脚本以 DOM Document 格式解析 response.body ,并执行以下操作:
使用 getElementsByTagName() 获取所有 food 元素。
确保至少存在一个 food 元素。
选择第一个 food 元素。 然后,使用 textContent 提取其嵌套的 name 和 calories 元素的文本值。
使用 client.assert() 验证提取的值是否与预期值一致。
2026年 3月 24日