Rest Assured使用resp.asString()获取响应时JSON解析失败求助
问题
作为Rest Assured初学者,调用resp.asString()获取API响应字符串时触发错误:
Failed to parse the JSON document
The JSON input text should neither be null nor empty
基础代码如下:
PrintStream log = new PrintStream(new FileOutputStream("Log.txt")); RequestSpecification req = new RequestSpecBuilder() .setBaseUri("https://rahulshettyacademy.com") .setContentType("application/json") .build(); // Define the ResponseSpecification to expect a status code of 201 ResponseSpecification res = new ResponseSpecBuilder() .expectStatusCode(201) .build(); // Method to make API request public void addAPI() { // Create the request object for the Google Maps API Googlemapssetters map = new Googlemapssetters(); Location location = new Location(); location.setLatitude(23.763); location.setLongi(31.895); map.setLocation(location); map.setAccuracy(57); map.setLangauge("Tamil"); map.setAddress("119, Misa Washington street, kk nagar"); map.setName("Abimanyau"); map.setPhone("6872658285"); List<String> types = new ArrayList<>(); types.add("Fridge"); types.add("Geyser"); map.setTypes(types); map.setWebsite("www.jaslogo.com"); // Sending the API request Response resp = given() .spec(req) .queryParam("key", "qaclick123") .header("Content-type", "application/json") .body(map) .log().all() .when() .post("/maps/api/place/add/json") .then() .log().all() .extract() .response(); System.out.println(resp.jsonPath().prettyPrint()); // Handling response if (resp.getStatusCode() == 200 || resp.getStatusCode() == 201) { System.out.println(resp.asString()); // --> Got the error here } }
解决方案
核心原因
你先调用了resp.jsonPath().prettyPrint(),这个方法会一次性消耗响应体的输入流,后续再调用resp.asString()时,响应体已经是空的,所以触发JSON解析错误。
具体解决办法
1. 只读取一次响应体
如果已经通过jsonPath().prettyPrint()打印了格式化后的响应,就不需要再调用asString();或者直接读取字符串后按需处理:
// 先读取响应体字符串 String responseBody = resp.asString(); // 打印原始字符串 System.out.println(responseBody); // 如果需要格式化JSON,基于字符串创建JsonPath再打印 System.out.println(new JsonPath(responseBody).prettyPrint());
2. 启用响应体缓存
提取响应时配置缓存,允许多次读取响应体:
Response resp = given() .spec(req) .queryParam("key", "qaclick123") .header("Content-type", "application/json") .body(map) .log().all() .when() .post("/maps/api/place/add/json") .then() .log().all() .extract() .response() .thenReturn(); // 启用缓存,支持多次读取响应体 // 现在可以同时调用两种方法 System.out.println(resp.jsonPath().prettyPrint()); System.out.println(resp.asString());
3. 统一状态码校验逻辑
你定义的ResponseSpecification期望状态码201,但代码里又判断200或201,建议保持一致。如果接口可能返回200,修改响应规格:
import static org.hamcrest.Matchers.*; ResponseSpecification res = new ResponseSpecBuilder() .expectStatusCode(anyOf(is(200), is(201))) .build();
内容的提问来源于stack exchange,提问作者Karthick Sudhakar
相关产品推荐
相关产品推荐

