How to handle responses in text format in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can handle responses in text format in Rest Assured. For this, we need to configure Rest Assured such that it can grasp a plain/text type Response. We need to use the registerParser method which is a part of the RestAssured class. Then pass text/plain and Parser.Text as parameters to the registerParser method.

We shall first send a GET request via Postman on a mock API URL and then observed its Response.

Using Rest Assured, we shall obtain the Response body - Tutorialspoint in text format.

Example

Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import io.restassured.parsing.Parser;
import io.restassured.response.Response;
public class NewTest {
   @Test
   public void getResponsePlainTxt() {

      //base URL
      RestAssured.baseURI = "https://run.mocky.io/v3";
      RestAssured.basePath ="/11ecb510-6bce-4d4f-97fd-87e4b272ca2c";

      //to handle plain/text response
      RestAssured.registerParser("text/plain", Parser.TEXT);

      //obtain response
      Response r= given()
      .when().get();

      //obtain response as string
      String t =r.asString();
      System.out.println(t);
   }
}

Output

raja
Updated on 17-Nov-2021 13:09:42

Advertisements