如何获取RestAPI中GET请求的响应体?RestAssured返回对象异常求助
解决RestAssured GET请求返回
io.restassured.internal.RestAssuredResponseImpl@xxx而非JSON响应体的问题 嗨,我刚碰到过一模一样的问题,其实本质是你没正确提取响应体内容!
你现在的代码直接返回了RestAssured的Response对象,当你打印这个对象时,默认调用的是它的toString()方法,输出的自然是对象的内存地址(也就是你看到的io.restassured.internal.RestAssuredResponseImpl@35adf623),而不是接口返回的JSON响应体。POST方法正常应该是你之前处理时正确提取了响应体,才没出现这个问题。
给你几个实用的解决方法:
1. 返回字符串形式的JSON响应体
修改你的方法,调用getBody().asString()来提取响应体的字符串内容:
public static String getResponseWithGetMethod() throws Exception { Response response = RequestInvoker.invokeGET(); // 获取响应体的字符串形式 return response.getBody().asString(); }
这样返回的结果就是你期望的{ "path1": true, "path2": true, "path3": true }格式了。
2. 返回JsonPath对象方便后续解析/断言
如果需要对响应体做进一步的JSON解析或者断言,可以直接返回JsonPath对象:
public static JsonPath getGetResponseJson() throws Exception { Response response = RequestInvoker.invokeGET(); return response.jsonPath(); }
后续使用示例:
// 获取指定字段的值 JsonPath jsonResponse = getGetResponseJson(); boolean path1Status = jsonResponse.getBoolean("path1"); // 直接做断言验证 RequestInvoker.invokeGET() .then() .assertThat() .body("path1", equalTo(true)) .body("path2", equalTo(true));
总结一下:RestAssured的Response对象本身只是一个封装了响应信息的容器,要拿到实际的响应体内容,必须通过getBody()相关的方法来提取,不能直接返回或打印Response对象本身哦!
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

