简体   繁体   中英

How to post complex XML using rest assured

Using rest-assured we can easily perform GET, POST and other methods. In the example below we are sending a POST to an API that returns a JSON response.

@Test
public void reserveARide()
{
    given().
        header("Authorization", "abcdefgh-123456").
        param("rideId", "gffgr-3423-gsdgh").
        param("guestCount", 2).
    when().
        post("http://someWebsite/reserveRide").
    then().
        contentType(ContentType.JSON).
        body("result.message", equalTo("success"));
}

But I need to create POST request with complex XML body. Body example:

<?xml version="1.0" encoding="UTF-8"?>
<request protocol="3.0" version="xxx" session="xxx">
<info1 param1="xxx" version="xxx" size="xxx" notes="xxx"/>
<info2 param1="xxx" version="xxx" size="xxx" notes="xxx"/>
</request>

How can I do this? Thank you in advance

I keep my bodies in the resources directory, and read them into a string using the following method:

public static String generateStringFromResource(String path) throws IOException {

    return new String(Files.readAllBytes(Paths.get(path)));

}

Then in my request I can say

String myRequest = generateStringFromResource("path/to/xml.xml")

        given()
            .contentType("application/xml")
            .body(myRequest)
        .when()
            .put("my.url/endpoint/")
        .then()
            statusCode(200)

I believe you can simply do this:

given().
    contentType("application/xml").
    body(yourbody).
...
...

You can also send serializable objects see: https://github.com/jayway/rest-assured/wiki/Usage#serialization

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