Response Content
The response body is accessed through the following method:
The ResponseContent class extends from the HttpClient HttpEntity class and provides several convenience methods:
InputStream
Reader
Reader
T
T
Future<T>
Future<T>
String
Future<String>
String
// Parse into a bean.
MyBean bean = client
.get(URI)
.run()
.getContent().as(MyBean.class);
// Parse into a linked-list of strings.
List<String> list1 = client
.get(URI)
.run()
.getContent().as(LinkedList.class, String.class);
// Parse into a linked-list of beans.
List<MyBean> list2 = client
.get(URI)
.run()
.getContent().as(LinkedList.class, MyBean.class);
// Parse into a linked-list of linked-lists of strings.
List<List<String>> list3 = client
.get(URI)
.run()
.getContent().as(LinkedList.class, LinkedList.class, String.class);
// Parse into a map of string keys/values.
Map<String,String> map1 = client
.get(URI)
.run()
.getContent().as(TreeMap.class, String.class, String.class);
// Parse into a map containing string keys and values of lists containing beans.
Map<String,List<MyBean>> map2 = client
.get(URI)
.run()
.getContent().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 ResponseContent.asString().
However, methods that involve reading directly from the input stream cannot be called twice.
In these cases, the RestResponse.cacheContent() and ResponseContent.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()
.cacheContent()
.getContent().pipeTo(someOtherStream)
.getContent().asInputStream();
Assertion methods are also provided for fluent-style calls:
// Assert that the body contains the string "Success".
String content = client
.get(URI)
.run()
.getContent().assertString().contains("Success")
.getContent().asString();
Object assertions allow you to parse the response body into a POJO and then perform various tests on that resulting POJO.
// Parse bean into POJO and then validate that it was parsed correctly.
MyBean bean = client.get(URI)
.run()
.getContent().assertObject(MyBean.class).asJson().is("{foo:'bar'}")
.getContent().as(MyBean.class);