drkvader
drkvader

Reputation: 173

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.

enter image description here

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

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

Headers enter image description here

Upvotes: 1

Views: 10893

Answers (2)

Wilfred Clement
Wilfred Clement

Reputation: 2774

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();

Upvotes: 1

Jimmy
Jimmy

Reputation: 1051

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();

Upvotes: 0

Related Questions