如何使用RestAssured发送多部分请求?

8

我有一个带有如下签名的方法的@Controller:

@PostMapping
@ResponseBody
public ResponseEntity<Result> uploadFileAndReturnJson(@RequestParam("file") MultipartFile file) {}

我希望能够构建多部分请求,而不需要实际创建任何文件。我尝试过像这样做:

private MultiPartSpecification getMultiPart() {
    return new MultiPartSpecBuilder("111,222")
            .mimeType(MimeTypeUtils.MULTIPART_FORM_DATA.toString())
            .controlName("file")
            .fileName("file")
            .build();
}

Response response = RestAssured.given(this.spec)
            .auth().basic("admin", "admin")
            .multiPart(getMultiPart())
            .when().post(URL);

很不幸,我收到了如下的回复:

所需的请求部分“file”不存在。

我尝试查看RestAssured单元测试,看起来我正在正确地进行。如果我尝试传递byte[]或InputStream而不是String,则会抛出异常:

无法使用不可重复的请求实体重试请求。

谢谢您的帮助。

3个回答

11

你的代码看起来很好,应该可以与byte[]一起使用。你可以像下面这样使用MultiPartSpecBuilder(byte[] content)

private MultiPartSpecification getMultiPart() {
         return new MultiPartSpecBuilder("Test-Content-In-File".getBytes()).
                fileName("book.txt").
                controlName("file").
                mimeType("text/plain").
                build();
   }

获取 byte[] 错误的详细信息可在https://github.com/rest-assured/rest-assured/issues/507查看。根据此,您应尝试像以下这样使用预先授权的基本身份验证。

.auth().preemptive.basic("admin", "admin")

1
try {

    RestAssured.given()
            .header(new Header("content-type", "multipart/form-data"))
            .multiPart("file",new File( "./src/main/resources/test.txt"))
            .formParam("description", "This is my doc")
            .auth().preemptive().basic(loginModel.getUsername(), loginModel.getPassword())
            .when()
            .post(URL)
            .then()
            .assertThat()
            .body(matchesJsonSchemaInClasspath("schemas/members/member-document.json"));
}
catch(Exception e) {
    Assert.assertEquals(false, true);
    logger.error(e.getMessage(), e);
}

0

我需要发送多个带有文件和JSON数据的请求,我是这样解决的

public static Response Post(JSONObject body, String URL, String file1, String file2) {
        try {
            return RestAssured.given().baseUri(URL).urlEncodingEnabled(false)
                    .accept("application/json, text/plain, */*")
                    .multiPart("data",body,"application/json")
                    .multiPart("file[0]", new File(file1),"multipart/form-data")
                    .multiPart("file[1]", new File(file2),"multipart/form-data")
                    .relaxedHTTPSValidation().when().post();
        } catch (Exception e) {
            System.out.println(e);
            return null;
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接