Rest Assured发送multipart/form-data格式POST请求传JSON和文件的实现问题
错误原因排查
415状态码代表服务端不支持请求的媒体类型,你当前代码直接将JSON字符串作为请求体发送,默认ContentType为application/json,不符合接口要求的multipart/form-data格式,且参数传递形式不符合要求:接口要求JSON内容作为form表单的body字段传递,而非直接放在请求体中。
问题1:仅提交JSON Payload的实现代码
你需要用multiPart方法指定表单字段传递JSON内容,代码示例:
import java.nio.file.Files; import java.nio.file.Paths; import static io.restassured.RestAssured.given; public class MultipartRequestTest { public void sendJsonOnlyRequest() throws Exception { String jsonFilePath = "<<Path to JSON File>>/Test_new.json"; String jsonContent = new String(Files.readAllBytes(Paths.get(jsonFilePath))); String res = "<你的认证TOKEN>"; String postUrl = "<<POST RESOURCE URL>>"; String response = given() .log().all() .header("X-AUTH-TOKEN", res) // 指定multipart表单的body字段,内容为JSON,指定内容类型为application/json .multiPart("body", "", jsonContent, "application/json") .when() .post(postUrl) .then() .log().body() .assertThat().statusCode(200) .extract().response().asString(); } }
上述代码会自动设置ContentType为multipart/form-data,无需手动指定header。
问题2:同时上传文件的实现代码
新增files字段的multipart配置即可,代码示例:
import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import static io.restassured.RestAssured.given; public class MultipartRequestTest { public void sendJsonWithFileRequest() throws Exception { String jsonFilePath = "<<Path to JSON File>>/Test_new.json"; String jsonContent = new String(Files.readAllBytes(Paths.get(jsonFilePath))); // 要上传的本地文件路径,支持.log等任意格式 File uploadFile = new File("<<Path to Upload File>>/test.log"); String res = "<你的认证TOKEN>"; String postUrl = "<<POST RESOURCE URL>>"; String response = given() .log().all() .header("X-AUTH-TOKEN", res) // 传递JSON的body字段 .multiPart("body", "", jsonContent, "application/json") // 传递文件的files字段 .multiPart("files", uploadFile.getName(), uploadFile, "application/octet-stream") .when() .post(postUrl) .then() .log().body() .assertThat().statusCode(200) .extract().response().asString(); } }
如果服务端对上传文件的ContentType有明确要求,把application/octet-stream替换为对应类型即可(比如文本日志文件可以用text/plain)。
内容的提问来源于stack exchange,提问作者user1865709
相关产品推荐
相关产品推荐

