使用RestAssured如何设置form-data格式请求体并添加键值对
Rest-Assured form-data格式请求修改方案
修改后完整代码
import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; public class RestAssuredRequests { @BeforeMethod public static void setup() { RestAssured.baseURI = "https://TEST/login"; } @Test public void postRequest() { Response response = given() // 显式指定form-data格式,也可以省略,使用formParam时RestAssured会自动适配 .contentType(ContentType.MULTIPART_FORM_DATA) // 逐个配置form-data键值对 .formParam("login", "login") .formParam("email", "TEST") .formParam("pass", "ATEST") // 新增键值对直接追加formParam即可,比如:.formParam("newKey", "newValue") // 若需上传文件可使用multiPart,比如:.multiPart("fileField", new File("本地文件路径")) .when() .post() .then() .extract().response(); System.out.println(response); //assertEquals(201, response.statusCode()); //assertEquals("foo", response.jsonPath().getString("title")); //assertEquals("bar", response.jsonPath().getString("body")); //assertEquals("1", response.jsonPath().getString("userId")); //assertEquals("101", response.jsonPath().getString("id")); } }
改动说明
- 移除原有JSON格式的
requestBody变量,form-data格式无需手动拼接请求字符串 - 替换
given()中的.body(requestBody)配置,改用formParam()方法逐个设置键值对,新增、调整键值对直接新增、修改对应formParam的参数即可 - 如果需要上传文件,可将对应参数替换为
.multiPart("文件字段名", new File("本地文件路径")),RestAssured会自动处理文件编码逻辑
内容的提问来源于stack exchange,提问作者DtestA
相关产品推荐
相关产品推荐

