RestAssured提取API响应access_token及整数类型识别问题
问题解决:提取嵌套access_token + RestAssured整数类型识别问题
一、正确提取嵌套结构里的access_token
你的API响应中,access_token嵌套在data对象下,原代码的jsonPath路径错误,需修改为data.access_token才能正确取值。
修改后的getToken()方法:
private String getToken() { RestAssured.baseURI = "https://raudhahku.com.my/api/v1/oauth/token"; RequestSpecification requestSpecification = RestAssured.given(); JSONObject requestParams = new JSONObject(); requestParams.put("grant_type", "client_credentials"); requestParams.put("client_id", 1); requestParams.put("client_secrets", "Gsv7brPlt5fIpqa1ebFc5A1uHwDJBPY6TRaMm8wa"); requestSpecification.header("Content-Type", "application/json"); requestSpecification.body(requestParams.toString()); Response response = RestAssured.post(); int statusCode = response.getStatusCode(); System.out.println(statusCode); // 修正jsonPath路径,获取嵌套在data里的access_token return response.body().jsonPath().getString("data.access_token"); }
二、解决RestAssured中整数被误识别为字符串的问题
问题原因
当前使用JSONObject的put方法传入整数(如client_id=1),调用toString()后整数会被序列化为字符串类型(如"client_id": "1"),导致API接收到的参数类型不符合预期;此外,RestAssured解析响应时也可能因序列化/反序列化配置问题,导致整数被识别为字符串。
解决方案
方案1:使用HashMap代替JSONObject
HashMap会保留原始数据类型,RestAssured会自动完成正确序列化:
private String getToken() { RestAssured.baseURI = "https://raudhahku.com.my/api/v1/oauth/token"; RequestSpecification requestSpecification = RestAssured.given(); Map<String, Object> requestParams = new HashMap<>(); requestParams.put("grant_type", "client_credentials"); requestParams.put("client_id", 1); // 保留Integer类型 requestParams.put("client_secrets", "Gsv7brPlt5fIpqa1ebFc5A1uHwDJBPY6TRaMm8wa"); requestSpecification.header("Content-Type", "application/json"); requestSpecification.body(requestParams); // 直接传入Map,RestAssured自动序列化 Response response = RestAssured.post(); int statusCode = response.getStatusCode(); System.out.println(statusCode); return response.body().jsonPath().getString("data.access_token"); }
方案2:配置RestAssured使用Gson序列化
引入Gson库实现更灵活的序列化控制,确保类型正确:
- 引入Gson依赖(Maven示例):
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency>
- 配置RestAssured使用Gson:
RestAssured.config = RestAssured.config().objectMapperConfig( new ObjectMapperConfig().gsonObjectMapperFactory((type, s) -> new Gson()) );
- 之后可直接用POJO类或Map作为请求体,类型都会被正确处理。
方案3:解析响应时强制转换类型
若响应中的整数被识别为字符串,提取时可强制转换:
// 提取expires_in并强制转为Integer Integer expiresIn = response.body().jsonPath().getInt("data.expires_in");
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

