简体   繁体   中英

How to send a POST with form-data in Body in RestAssured setting multipart with a specific content-type

Trying to send a POST request with form-data in Body in RestAssured, however not sure how should do it. In Postman, it's fine.

在此处输入图像描述

I've tried things like:

public Response create() {
    return super
            .given()
            .contentType("multipart/form-data")
            .multiPart("MetaDataOne", new File("file.txt"))
            .multiPart("MetaDataTwo", new File("file2.txt"))
            .basePath("/create")
            .log().all()
            .post()
            .then()
            .log().all()
            .extract()
            .response();
}

But seems that my files are not being sent in the request.

Console log

Multiparts

  • Content-Disposition form-data; name = MetadataOne; filename = file
  • Content-Type: application/octet-stream

{"error": 415, "description": Content type application/octet-stream not supported}

Headers在此处输入图像描述

Can you try with this, This should overwrite the Content-Type as multipart/form-data rather than application/octet-stream

given().contentType("multipart/form-data").multiPart("MetaDataOne", new File("file.txt"), "multipart/form-data")
                .multiPart("MetaDataTwo", new File("file2.txt"), "multipart/form-data").basePath("/create").log().all()
                .post().then().log().all().extract().response();

It's very simple to consume a RESTFull webservice Api, just follow these simple steps

Step 1: Create a Request Object pointing to the Service

RestAssured.baseURI ="https://myhost.com/xyz";
RequestSpecification request = RestAssured.given();

Step 2: Create a JSON object which contains all the form fields

JSONObject jsonObject = new JSONObject();
jsonObject.put("Form_Field_1", "Input Value 1"); 
jsonObject.put("Form_Field_2", "Input Value 2");
jsonObject.put("Form_Field_3", "Input Value 3");
jsonObject.put("Form_Field_4", "Input Value 4");

Step 3: Add JSON object in the request body and send the Request

request.header("Content-Type", "application/json");
request.body(jsonObject.toJSONString());

Post the request and check the response

Response response = request.post("/register");

Step 4: Validate the Response

int statusCode = response.getStatusCode();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM