bodyString method

String bodyString(
  1. Encoding encoding
)

Retrieves the body as a String.

If the source format of the body is a String, it is returned and the encoding is not used.

If the source format of the body is a sequence of bytes, it is converted to a String using the decoder of the encoding. Note: if the encoding is utf8, this method may throw a FormatException when the bytes do not represent a valid UTF-8 encoded code point.

If there is no source for the body, returns the empty string.

Related methods

Use bodyBytes to retrieve the body as a sequence of bytes.

Use bodyStr as a shorthand for invoking this method with the utf8 encoding.

If retrieving the String to only see if it is empty, use bodyIsEmpty instead (which works more efficiently if the body had been set to a sequence of bytes, since it doesn't need to decode them).

Implementation

String bodyString(Encoding encoding) {
  switch (_body) {
    case SimulatedResponseBodyType.none:
      return ''; // empty String
    case SimulatedResponseBodyType.bytes:
      return encoding.decode(_bodyBytes!);
    case SimulatedResponseBodyType.string:
      return _bodyStr!;
  }
}