Charles模拟接口响应
步骤:
- 准备一个包含完整HTTP响应的文件(包括状态行、头部和响应体)。
- 在Charles中为该接口设置Map Local,指向这个文件。
- 确保Map Local设置已启用。
500_error.txt
HTTP/1.1 500 Internal Server Error // 关键:强制指定状态码
Content-Type: application/json // 按需修改类型
X-Custom-Header: error // 可选自定义头
{
"status": 500,
"error": "Internal Server Error",
"message": "服务端模拟错误"
}
注意:
- 第一行必须是HTTP状态行(
HTTP/1.1 500 Internal Server Error)。 - 接下来是响应头,至少要有
Content-Type和Connection。Content-Type根据实际情况设置,这里我们用JSON。 - 然后空一行(必须),接着是响应体(即你希望返回的JSON内容)。
417_error.txt
HTTP/1.1 417 Expectation Failed
Content-Type: application/json
X-Mocked-By: Charles
{
"error": {
"code": 417,
"message": "Expectation Failed",
"details": "Server cannot meet requirements of Expect header"
}
}
常见问题解决:
状态码不生效 → 检查响应文件首行是否为 HTTP/1.1 500
内容未更新 → 关闭 Charles 重新打开映射文件

浙公网安备 33010602011771号