You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

REST Assured发送非UTF-8字符JSON请求乱码问题求助

解决REST Assured发送非UTF-8字符乱码问题

出现这个问题的核心原因是REST Assured默认未在请求的Content-Type头中明确指定charset=UTF-8,且序列化请求体时可能未强制使用UTF-8编码;而Postman会自动添加该字符集声明,因此服务器能正确解析。以下是几种可行的解决方法:

1. 单个请求中明确指定带字符集的Content-Type

在请求中直接设置Content-Type为application/json; charset=UTF-8,确保服务器识别请求体的编码格式:

发送JSON字符串的情况:

given()
    .contentType("application/json; charset=UTF-8")
    .body("{\"billingAddress\": {\"address\": \"𠜎\"}}")
.when()
    .post("/your-target-endpoint")
.then()
    .statusCode(200);

发送POJO对象的情况:

// 假设已定义对应POJO类
BillingAddress billingAddr = new BillingAddress();
billingAddr.setAddress("𠜎");
OrderRequest request = new OrderRequest();
request.setBillingAddress(billingAddr);

given()
    .contentType(ContentType.JSON.withCharset("UTF-8"))
    .body(request)
.when()
    .post("/your-target-endpoint")
.then()
    .statusCode(200);

2. 全局配置REST Assured默认编码

如果所有请求都需要使用UTF-8编码,可以全局配置编码器,避免重复设置:

// 在测试类初始化或全局配置类中设置
RestAssured.config = RestAssured.config()
    .encoderConfig(EncoderConfig.encoderConfig().defaultContentCharset("UTF-8"));

3. 确保请求体字符串的UTF-8编码正确性

如果是从外部文件读取JSON内容,读取时需指定UTF-8编码,避免读取过程中出现乱码:

String jsonBody = new String(Files.readAllBytes(Paths.get("path/to/your/json/file.json")), StandardCharsets.UTF_8);

given()
    .contentType("application/json; charset=UTF-8")
    .body(jsonBody)
.when()
    .post("/your-target-endpoint");

内容的提问来源于stack exchange,提问作者Ivo Dimitrov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 06:42:39