RestAssured 是一个用于测试 RESTful web 服务的 Java 库。它提供了一种简洁的方式来发送 HTTP 请求并验证响应。通过 RestAssured,你可以轻松地将发送到服务器的请求保存为字符串或文件。
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class RestAssuredExample {
public static void main(String[] args) {
String responseString = RestAssured.get("https://api.example.com/data")
.asString();
System.out.println(responseString);
}
}
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class RestAssuredExample {
public static void main(String[] args) {
Response response = RestAssured.get("https://api.example.com/data");
File file = new File("response.txt");
try (FileWriter writer = new FileWriter(file)) {
writer.write(response.getBody().asString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
原因:
解决方法:
import io.restassured.RestAssured;
import io.restassured.response.Response;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class RestAssuredExample {
public static void main(String[] args) {
Response response = RestAssured.get("https://api.example.com/data");
File file = new File("response.txt");
try (FileWriter writer = new FileWriter(file)) {
String responseBody = response.getBody().asString();
writer.write(responseBody);
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过以上方法,你可以轻松地将 RestAssured 发送的请求响应保存为字符串或文件,并解决常见的保存问题。
领取专属 10元无门槛券
手把手带您无忧上云