{8.2.0-new} Response Body

The response body is accessed through the following method:

The {@link oajr.client2.RestResponseBody} class extends from the HttpClient {@link org.apache.http.HttpEntity} class and provides several convenience methods:

Examples:

// Parse into a bean. MyBean bean = client .get(URI) .run() .getBody().as(MyBean.class); // Parse into a linked-list of strings. List<String> l1 = client .get(URI) .run() .getBody().as(LinkedList.class, String.class); // Parse into a linked-list of beans. List<MyBean> l2 = client .get(URI) .run() .getBody().as(LinkedList.class, MyBean.class); // Parse into a linked-list of linked-lists of strings. List<List<String>> l3 = client .get(URI) .run() .getBody().as(LinkedList.class, LinkedList.class, String.class); // Parse into a map of string keys/values. Map<String,String> m4 = client .get(URI) .run() .getBody().as(TreeMap.class, String.class, String.class); // Parse into a map containing string keys and values of lists containing beans. Map<String,List<MyBean>> m5 = client .get(URI) .run() .getBody().as(TreeMap.class, String.class, List.class, MyBean.class);

The response body can only be consumed once unless it has been cached into memory. In many cases, the body is automatically cached when using the assertions methods or methods such as {@link oajr.client2.RestResponseBody#asString()}. However, methods that involve reading directly from the input stream cannot be called twice. In these cases, the {@link oajr.client2.RestResponse#cacheBody()} and {@link oajr.client2.RestResponseBody#cache()} methods are provided to cache the response body in memory so that you can perform several operations against it.

// Cache the response body so we can access it twice. InputStream inputStream = client .get(URI) .run() .cacheBody() .getBody().pipeTo(someOtherStream) .getBody().asInputStream();

Assertion methods are also provided for fluent-style calls:

Example:

// Assert that the body contains the string "Success". String body = client .get(URI) .run() .getBody().assertString().contains("Success") .getBody().asString();

Object assertions allow you to parse the response body into a POJO and then perform various tests on that resulting POJO.

Example:

// Parse bean into POJO and then validate that it was parsed correctly. MyBean bean = client.get(URI) .run() .getBody().assertObject(MyBean.class).json().is("{foo:'bar'}") .getBody().as(MyBean.class);