How to send form-data in api using Rest-assured

感情迁移 提交于 2021-02-07 12:31:46

问题


I want to send below as a form-data in API Body for a PUT request:

  1. Upload a file(KEY) with "Error.png"(VALUE)
  2. Send text, "MyName"(KEY) with false(VALUE)

How to do this using REST-Assured

Attached is the screenshot Form-Data Image


回答1:


You need to set desired content type i.e "multipart/form-data" and add the multipart request specs to the request. Eg.

        given()
            .contentType("multipart/form-data")
            .multiPart("file", "filename")
            .multiPart("key", "value")
            .when()
            .put(endpoint);



回答2:


Be sure to include a file object if you're doing a file upload. It should look like this:

given()
    .contentType("multipart/form-data")
    .multiPart("id", "123")
    .multiPart("file", new File("./src/test/resources/test-file.txt"))
    .post("api/endpoint")
.then()
    ...



回答3:


Most of the times we need to convert image into readFileToByteArray.

    String file = "/Users/Downloads/file.png";

    byte[] fileContent = FileUtils.readFileToByteArray(new File(file));

    RestAssured.baseURI = "Enter Base uri";

    Response res = given()

            .header("Accept", "application/json")
            .header("Content-type", "multipart/form-data")
            .formParam("token", "08bc73deff88dd3d44bb1bf65b55d4ff")
            .multiPart("asset", "image/png", fileContent).when()
            .post("api/endpoint");  

    System.out.println(res.getStatusCode());

    System.out.println(res.jsonPath().prettify());  

Please make sure the image mime type (specified in the example as "image/png").



来源:https://stackoverflow.com/questions/48262096/how-to-send-form-data-in-api-using-rest-assured

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!