You need to enable JavaScript to run this app. 使用RestAssured如何设置form-data格式请求体并添加键值对
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 17:39:03