Class ResponseContent

java.lang.Object
org.apache.juneau.rest.client.ResponseContent
All Implemented Interfaces:
HttpEntity

public class ResponseContent extends Object implements HttpEntity
Represents the body of an HTTP response.

An extension of an HttpClient HttpEntity that provides various support for converting the body to POJOs and other convenience methods.

See Also:
  • Constructor Details

    • ResponseContent

      public ResponseContent(RestClient client, RestRequest request, RestResponse response, Parser parser)
      Constructor.
      Parameters:
      client - The client used to build this request.
      request - The request object.
      response - The response object.
      parser - The parser to use to consume the body. Can be null.
  • Method Details

    • parser

      public ResponseContent parser(Parser value)
      Specifies the parser to use for this body.

      If not specified, uses the parser defined on the client set via RestClient.Builder.parser(Class).

      Parameters:
      value - The new part parser to use for this body.
      Returns:
      This object.
    • schema

      Specifies the schema for this body.

      Used by schema-based parsers such as OpenApiParser.

      Parameters:
      value - The schema.
      Returns:
      This object.
    • cache

      Causes the contents of the response body to be stored so that it can be repeatedly read.

      Calling this method allows methods that read the response body to be called multiple times.

      Notes:
      • Multiple calls to this method are ignored.
      Returns:
      This object.
    • asInputStream

      Returns the HTTP response message body as an input stream.
      Notes:
      • Once this input stream is exhausted, it will automatically be closed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Returns:
      The HTTP response message body input stream, never null.
      For responses without a body(e.g. HTTP 204), returns an empty stream.
      Throws:
      IOException - If a stream or illegal state exception was thrown.
    • asReader

      public Reader asReader() throws IOException
      Returns the HTTP response message body as a reader based on the charset on the Content-Type response header.
      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • Once this input stream is exhausted, it will automatically be closed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Returns:
      The HTTP response message body reader, never null.
      For responses without a body(e.g. HTTP 204), returns an empty reader.
      Throws:
      IOException - If an exception occurred.
    • asReader

      public Reader asReader(Charset charset) throws IOException
      Returns the HTTP response message body as a reader using the specified charset.
      Notes:
      • Once this input stream is exhausted, it will automatically be closed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Parameters:
      charset - The charset to use for the reader.
      If null, "UTF-8" is used.
      Returns:
      The HTTP response message body reader, never null.
      For responses without a body(e.g. HTTP 204), returns an empty reader.
      Throws:
      IOException - If an exception occurred.
    • asBytes

      public byte[] asBytes() throws RestCallException
      Returns the HTTP response message body as a byte array. The HTTP response message body reader, never null.
      For responses without a body(e.g. HTTP 204), returns an empty array.
      Returns:
      The HTTP response body as a byte array.
      Throws:
      RestCallException - If an exception occurred.
    • pipeTo

      Pipes the contents of the response to the specified output stream.
      Notes:
      • The output stream is not automatically closed.
      • Once the input stream is exhausted, it will automatically be closed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Parameters:
      os - The output stream to pipe the output to.
      Returns:
      This object.
      Throws:
      IOException - If an IO exception occurred.
    • pipeTo

      Pipes the contents of the response to the specified writer.
      Notes:
      • The writer is not automatically closed.
      • Once the reader is exhausted, it will automatically be closed.
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Parameters:
      w - The writer to pipe the output to.
      Returns:
      This object.
      Throws:
      IOException - If an IO exception occurred.
    • pipeTo

      public RestResponse pipeTo(Writer w, Charset charset) throws IOException
      Pipes the contents of the response to the specified writer.
      Notes:
      • The writer is not automatically closed.
      • Once the reader is exhausted, it will automatically be closed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Parameters:
      w - The writer to pipe the output to.
      charset - The charset to use for the reader.
      If null, "UTF-8" is used.
      Returns:
      This object.
      Throws:
      IOException - If an IO exception occurred.
    • pipeTo

      public RestResponse pipeTo(Writer w, boolean byLines) throws IOException
      Pipes the contents of the response to the specified writer.
      Notes:
      • The writer is not automatically closed.
      • Once the reader is exhausted, it will automatically be closed.
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Parameters:
      w - The writer to write the output to.
      byLines - Flush the writers after every line of output.
      Returns:
      This object.
      Throws:
      IOException - If an IO exception occurred.
    • pipeTo

      public RestResponse pipeTo(Writer w, Charset charset, boolean byLines) throws IOException
      Pipes the contents of the response to the specified writer.
      Notes:
      • The writer is not automatically closed.
      • Once the reader is exhausted, it will automatically be closed.
      • This method can be called multiple times if cache() has been called.
      • Calling this method multiple times without caching enabled will cause a RestCallException with an inner IllegalStateException to be thrown.
      Parameters:
      w - The writer to pipe the output to.
      byLines - Flush the writers after every line of output.
      charset - The charset to use for the reader.
      If null, "UTF-8" is used.
      Returns:
      This object.
      Throws:
      IOException - If an IO exception occurred.
    • as

      public <T> T as(Type type, Type... args) throws RestCallException
      Parses HTTP body into the specified object type.

      The type can be a simple type (e.g. beans, strings, numbers) or parameterized type (collections/maps).

      Examples:

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

      Collection classes are assumed to be followed by zero or one objects indicating the element type.

      Map classes are assumed to be followed by zero or two meta objects indicating the key and value types.

      The array can be arbitrarily long to indicate arbitrarily complex data structures.

      Notes:
      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      type - The object type to create.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      args - The type arguments of the class if it's a collection or map.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      Ignored if the main type is not a map or collection.
      Returns:
      The parsed object.
      Throws:
      RestCallException -
      • If the input contains a syntax error or is malformed, or is not valid for the specified type.
      • If a connection error occurred.
      See Also:
    • as

      public <T> T as(Class<T> type) throws RestCallException
      Same as as(Type,Type...) except optimized for a non-parameterized class.

      This is the preferred parse method for simple types since you don't need to cast the results.

      Examples:

      // Parse into a string. String string = client.get(URI).run().getContent().as(String.class); // Parse into a bean. MyBean bean = client.get(URI).run().getContent().as(MyBean.class); // Parse into a bean array. MyBean[] beanArray = client.get(URI).run().getContent().as(MyBean[].class); // Parse into a linked-list of objects. List list = client.get(URI).run().getContent().as(LinkedList.class); // Parse into a map of object keys/values. Map map = client.get(URI).run().getContent().as(TreeMap.class);

      Notes:
      Type Parameters:
      T - The class type of the object being created. See as(Type,Type...) for details.
      Parameters:
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      RestCallException - If the input contains a syntax error or is malformed, or is not valid for the specified type, or if a connection error occurred.
    • as

      public <T> T as(ClassMeta<T> type) throws RestCallException
      Same as as(Class) except allows you to predefine complex data types using the ClassMeta API.
      Examples:

      BeanContext beanContext = BeanContext.DEFAULT; // Parse into a linked-list of strings. ClassMeta<List<String>> cm1 = beanContext.getClassMeta(LinkedList.class, String.class); List<String> list1 = client.get(URI).run().getContent().as(cm1); // Parse into a linked-list of beans. ClassMeta<List<String>> cm2 = beanContext.getClassMeta(LinkedList.class, MyBean.class); List<MyBean> list2 = client.get(URI).run().getContent().as(cm2); // Parse into a linked-list of linked-lists of strings. ClassMeta<List<String>> cm3 = beanContext.getClassMeta(LinkedList.class, LinkedList.class, String.class); List<List<String>> list3 = client.get(URI).run().getContent().as(cm3); // Parse into a map of string keys/values. ClassMeta<List<String>> cm4 = beanContext.getClassMeta(TreeMap.class, String.class, String.class); Map<String,String> map4 = client.get(URI).run().getContent().as(cm4); // Parse into a map containing string keys and values of lists containing beans. ClassMeta<List<String>> cm5 = beanContext.getClassMeta(TreeMap.class, String.class, List.class, MyBean.class); Map<String,List<MyBean>> map5 = client.get(URI).run().getContent().as(cm5);

      Notes:
      Type Parameters:
      T - The class type of the object to create.
      Parameters:
      type - The object type to create.
      Returns:
      The parsed object.
      Throws:
      RestCallException -
      • If the input contains a syntax error or is malformed, or is not valid for the specified type.
      • If a connection error occurred.
      See Also:
    • asFuture

      public <T> Future<T> asFuture(Class<T> type) throws RestCallException
      Same as as(Class) but allows you to run the call asynchronously.
      Notes:
      Type Parameters:
      T - The class type of the object being created.
      Parameters:
      type - The object type to create.
      Returns:
      The future object.
      Throws:
      RestCallException - If the executor service was not defined.
      See Also:
    • asFuture

      public <T> Future<T> asFuture(ClassMeta<T> type) throws RestCallException
      Same as as(ClassMeta) but allows you to run the call asynchronously.
      Notes:
      Type Parameters:
      T - The class type of the object being created. See as(Type, Type...) for details.
      Parameters:
      type - The object type to create.
      Returns:
      The future object.
      Throws:
      RestCallException - If the executor service was not defined.
      See Also:
    • asFuture

      public <T> Future<T> asFuture(Type type, Type... args) throws RestCallException
      Same as as(Type,Type...) but allows you to run the call asynchronously.
      Notes:
      Type Parameters:
      T - The class type of the object being created. See as(Type, Type...) for details.
      Parameters:
      type - The object type to create.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      args - The type arguments of the class if it's a collection or map.
      Can be any of the following: ClassMeta, Class, ParameterizedType, GenericArrayType
      Ignored if the main type is not a map or collection.
      Returns:
      The future object.
      Throws:
      RestCallException - If the executor service was not defined.
      See Also:
    • asString

      Returns the contents of this body as a string.
      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • This method automatically calls cache() so that the body can be retrieved multiple times.
      • The input stream is automatically closed after this call.
      Returns:
      The response as a string.
      Throws:
      RestCallException -
      • If the input contains a syntax error or is malformed, or is not valid for the specified type.
      • If a connection error occurred.
    • asStringFuture

      Same as asString() but allows you to run the call asynchronously.
      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • This method automatically calls cache() so that the body can be retrieved multiple times.
      • The input stream is automatically closed after this call.
      Returns:
      The future object.
      Throws:
      RestCallException - If the executor service was not defined.
      See Also:
    • asAbbreviatedString

      public String asAbbreviatedString(int length) throws RestCallException
      Same as asString() but truncates the string to the specified length.

      If truncation occurs, the string will be suffixed with "...".

      Parameters:
      length - The max length of the returned string.
      Returns:
      The truncated string.
      Throws:
      RestCallException - If a problem occurred trying to read from the reader.
    • asHex

      public String asHex() throws RestCallException
      Returns the HTTP body content as a simple hexadecimal character string.
      Example:

      0123456789ABCDEF

      Returns:
      The incoming input from the connection as a plain string.
      Throws:
      RestCallException - If a problem occurred trying to read from the reader.
    • asSpacedHex

      Returns the HTTP body content as a simple space-delimited hexadecimal character string.
      Example:

      01 23 45 67 89 AB CD EF

      Returns:
      The incoming input from the connection as a plain string.
      Throws:
      RestCallException - If a problem occurred trying to read from the reader.
    • asObjectRest

      public ObjectRest asObjectRest(Class<?> innerType) throws RestCallException
      Parses the output from the body into the specified type and then wraps that in a ObjectRest.

      Useful if you want to quickly retrieve a single value from inside of a larger JSON document.

      Parameters:
      innerType - The class type of the POJO being wrapped.
      Returns:
      The parsed output wrapped in a ObjectRest.
      Throws:
      RestCallException -
      • If the input contains a syntax error or is malformed, or is not valid for the specified type.
      • If a connection error occurred.
    • asObjectRest

      Converts the output from the connection into an JsonMap and then wraps that in a ObjectRest.

      Useful if you want to quickly retrieve a single value from inside of a larger JSON document.

      Returns:
      The parsed output wrapped in a ObjectRest.
      Throws:
      RestCallException -
      • If the input contains a syntax error or is malformed, or is not valid for the specified type.
      • If a connection error occurred.
    • asMatcher

      public Matcher asMatcher(Pattern pattern) throws RestCallException
      Converts the contents of the response body to a string and then matches the specified pattern against it.
      Example:

      // Parse response using a regular expression. Matcher matcher = client .get(URI) .run() .getContent().asMatcher(Pattern.compile("foo=(.*)")); if (matcher.matches()) { String foo = matcher.group(1); }

      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • This method automatically calls cache() so that the body can be retrieved multiple times.
      • The input stream is automatically closed after this call.
      Parameters:
      pattern - The regular expression pattern to match.
      Returns:
      The matcher.
      Throws:
      RestCallException - If a connection error occurred.
    • asMatcher

      public Matcher asMatcher(String regex) throws RestCallException
      Converts the contents of the response body to a string and then matches the specified pattern against it.
      Example:

      // Parse response using a regular expression. Matcher matcher = client .get(URI) .run() .getContent().asMatcher("foo=(.*)"); if (matcher.matches()) { String foo = matcher.group(1); }

      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • If cache() or RestResponse.cacheContent() has been called, this method can be can be called multiple times and/or combined with other methods that retrieve the content of the response. Otherwise a RestCallException with an inner IllegalStateException will be thrown.
      • The input stream is automatically closed after this call.
      Parameters:
      regex - The regular expression pattern to match.
      Returns:
      The matcher.
      Throws:
      RestCallException - If a connection error occurred.
    • asMatcher

      public Matcher asMatcher(String regex, int flags) throws RestCallException
      Converts the contents of the response body to a string and then matches the specified pattern against it.
      Example:

      // Parse response using a regular expression. Matcher matcher = client .get(URI) .run() .getContent().asMatcher("foo=(.*)", MULTILINE & CASE_INSENSITIVE); if (matcher.matches()) { String foo = matcher.group(1); }

      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • If cache() or RestResponse.cacheContent() has been called, this method can be can be called multiple times and/or combined with other methods that retrieve the content of the response. Otherwise a RestCallException with an inner IllegalStateException will be thrown.
      • The input stream is automatically closed after this call.
      Parameters:
      regex - The regular expression pattern to match.
      flags - Pattern match flags. See Pattern.compile(String, int).
      Returns:
      The matcher.
      Throws:
      RestCallException - If a connection error occurred.
    • assertValue

      Provides the ability to perform fluent-style assertions on this response body.

      This method is called directly from the RestResponse.assertContent() method to instantiate a fluent assertions object.

      Examples:

      // Validates the response body equals the text "OK". client .get(URI) .run() .getContent().assertValue().equals("OK"); // Validates the response body contains the text "OK". client .get(URI) .run() .getContent().assertValue().contains("OK"); // Validates the response body passes a predicate test. client .get(URI) .run() .getContent().assertValue().is(x -> x.contains("OK")); // Validates the response body matches a regular expression. client .get(URI) .run() .getContent().assertValue().isPattern(".*OK.*"); // Validates the response body matches a regular expression using regex flags. client .get(URI) .run() .getContent().assertValue().isPattern(".*OK.*", MULTILINE & CASE_INSENSITIVE); // Validates the response body matches a regular expression in the form of an existing Pattern. Pattern pattern = Pattern.compile(".*OK.*"); client .get(URI) .run() .getContent().assertValue().isPattern(pattern);

      The assertion test returns the original response object allowing you to chain multiple requests like so:

      // Validates the response body matches a regular expression. MyBean bean = client .get(URI) .run() .getContent().assertValue().isPattern(".*OK.*"); .getContent().assertValue().isNotPattern(".*ERROR.*") .getContent().as(MyBean.class);

      Notes:
      • If no charset was found on the Content-Type response header, "UTF-8" is assumed.
      • This method automatically calls cache() so that the body can be retrieved multiple times.
      • The input stream is automatically closed after this call.
      Returns:
      A new fluent assertion object.
    • assertString

      Shortcut for calling assertValue().asString().
      Returns:
      A new fluent assertion.
    • assertBytes

      Shortcut for calling assertValue().asBytes().
      Returns:
      A new fluent assertion.
    • assertObject

      Shortcut for calling assertValue().as(type).
      Type Parameters:
      T - The object type to create.
      Parameters:
      type - The object type to create.
      Returns:
      A new fluent assertion.
    • assertObject

      Shortcut for calling assertValue().as(type, args).
      Type Parameters:
      T - The object type to create.
      Parameters:
      type - The object type to create.
      args - Optional type arguments.
      Returns:
      A new fluent assertion.
    • response

      Returns the response that created this object.
      Returns:
      The response that created this object.
    • isRepeatable

      public boolean isRepeatable()
      Tells if the entity is capable of producing its data more than once.

      A repeatable entity's getContent() and writeTo(OutputStream) methods can be called more than once whereas a non-repeatable entity's can not.

      Notes:
      • This method always returns true if the response body is cached (see cache()).
      Specified by:
      isRepeatable in interface HttpEntity
      Returns:
      true if the entity is repeatable, false otherwise.
    • isChunked

      public boolean isChunked()
      Tells about chunked encoding for this entity.

      The primary purpose of this method is to indicate whether chunked encoding should be used when the entity is sent.
      For entities that are received, it can also indicate whether the entity was received with chunked encoding.

      The behavior of wrapping entities is implementation dependent, but should respect the primary purpose.

      Specified by:
      isChunked in interface HttpEntity
      Returns:
      true if chunked encoding is preferred for this entity, or false if it is not.
    • getContentLength

      public long getContentLength()
      Tells the length of the content, if known.
      Specified by:
      getContentLength in interface HttpEntity
      Returns:
      The number of bytes of the content, or a negative number if unknown.
      If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.
    • getContentType

      Obtains the Content-Type header, if known.

      This is the header that should be used when sending the entity, or the one that was received with the entity. It can include a charset attribute.

      Specified by:
      getContentType in interface HttpEntity
      Returns:
      The Content-Type header for this entity, or null if the content type is unknown.
    • getContentEncoding

      Obtains the Content-Encoding header, if known.

      This is the header that should be used when sending the entity, or the one that was received with the entity.
      Wrapping entities that modify the content encoding should adjust this header accordingly.

      Specified by:
      getContentEncoding in interface HttpEntity
      Returns:
      The Content-Encoding header for this entity, or null if the content encoding is unknown.
    • getContent

      Returns a content stream of the entity.
      Notes:
      • This method is equivalent to asInputStream() which is the preferred method for fluent-style coding.
      • This input stream will auto-close once the end of stream has been reached.
      • It is up to the caller to properly close this stream if not fully consumed.
      • This method can be called multiple times if the entity is repeatable or the cache flag is set on this object.
      • Calling this method multiple times on a non-repeatable or cached body will throw a IllegalStateException. Note that this is different from the HttpClient specs for this method.
      Specified by:
      getContent in interface HttpEntity
      Returns:
      Content stream of the entity.
      Throws:
      IOException
      UnsupportedOperationException
    • writeTo

      public void writeTo(OutputStream outstream) throws IOException
      Writes the entity content out to the output stream.
      Notes:
      • This method is equivalent to pipeTo(OutputStream) which is the preferred method for fluent-style coding.
      Specified by:
      writeTo in interface HttpEntity
      Parameters:
      outstream - The output stream to write entity content to.
      Throws:
      IOException
    • isStreaming

      public boolean isStreaming()
      Tells whether this entity depends on an underlying stream.
      Notes:
      • This method always returns false if the response body is cached (see cache().
      Specified by:
      isStreaming in interface HttpEntity
      Returns:
      true if the entity content is streamed, false otherwise.
    • consumeContent

      @Deprecated public void consumeContent() throws IOException
      Deprecated.
      Use standard java convention to ensure resource deallocation by calling InputStream.close() on the input stream returned by getContent()
      This method is called to indicate that the content of this entity is no longer required.

      This method is of particular importance for entities being received from a connection.
      The entity needs to be consumed completely in order to re-use the connection with keep-alive.

      Specified by:
      consumeContent in interface HttpEntity
      Throws:
      IOException - If an I/O error occurs.
    • toString

      public String toString()
      Overrides:
      toString in class Object