Appearance
HttpResponse abstract interface
abstract interface class HttpResponse implements IOSinkAn HTTP response, which returns the headers and data from the server to the client in response to an HTTP request.
Every HttpRequest object provides access to the associated HttpResponse object through the response property. The server sends its response to the client by writing to the HttpResponse object.
Writing the response
This class implements IOSink. After the header has been set up, the methods from IOSink, such as writeln(), can be used to write the body of the HTTP response. Use the close() method to close the response and send it to the client.
dart
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});When one of the IOSink methods is used for the first time, the request header is sent. Calling any methods that change the header after it is sent throws an exception.
If no "Content-Type" header is set then a default of "text/plain; charset=utf-8" is used and string data written to the IOSink will be encoded using UTF-8.
Setting the headers
The HttpResponse object has a number of properties for setting up the HTTP headers of the response. When writing string data through the IOSink, the encoding used is determined from the "charset" parameter of the "Content-Type" header.
dart
HttpResponse response = ...
response.headers.contentType
= ContentType("application", "json", charset: "utf-8");
response.write(...); // Strings written will be UTF-8 encoded.If no charset is provided the default of ISO-8859-1 (Latin 1) will be used.
dart
HttpResponse response = ...
response.headers.add(HttpHeaders.contentTypeHeader, "text/plain");
response.write(...); // Strings written will be ISO-8859-1 encoded.If a charset is provided but it is not recognized, then the "Content-Type" header will include that charset but string data will be encoded using ISO-8859-1 (Latin 1).
Implemented types
Properties
bufferOutput read / write
bool bufferOutputgetter:
Gets or sets if the HttpResponse should buffer output.
Default value is true.
Note: Disabling buffering of the output can result in very poor performance, when writing many small chunks.
setter:
Gets or sets if the HttpResponse should buffer output.
Default value is true.
Note: Disabling buffering of the output can result in very poor performance, when writing many small chunks.
Implementation
dart
bool bufferOutput = true;connectionInfo no setter
HttpConnectionInfo? get connectionInfoGets information about the client connection. Returns null if the socket is not available.
Implementation
dart
HttpConnectionInfo? get connectionInfo;contentLength read / write
int contentLengthgetter:
Gets and sets the content length of the response. If the size of the response is not known in advance set the content length to -1, which is also the default if not set.
setter:
Gets and sets the content length of the response. If the size of the response is not known in advance set the content length to -1, which is also the default if not set.
Implementation
dart
int contentLength = -1;cookies no setter
Cookies to set in the client (in the 'set-cookie' header).
Implementation
dart
List<Cookie> get cookies;deadline read / write
Duration? deadlinegetter:
Set and get the deadline for the response. The deadline is timed from the time it's set. Setting a new deadline will override any previous deadline. When a deadline is exceeded, the response will be closed and any further data ignored.
To disable a deadline, set the deadline to null.
The deadline is null by default.
setter:
Set and get the deadline for the response. The deadline is timed from the time it's set. Setting a new deadline will override any previous deadline. When a deadline is exceeded, the response will be closed and any further data ignored.
To disable a deadline, set the deadline to null.
The deadline is null by default.
Implementation
dart
Duration? deadline;done no setter inherited
Future<dynamic> get doneA future that will complete when the consumer closes, or when an error occurs.
This future is identical to the future returned by close.
Inherited from IOSink.
Implementation
dart
Future get done;encoding read / write inherited
Encoding encodinggetter:
The Encoding used when writing strings.
Depending on the underlying consumer, this property might be mutable.
setter:
The Encoding used when writing strings.
Depending on the underlying consumer, this property might be mutable.
Inherited from IOSink.
Implementation
dart
late Encoding encoding;hashCode no setter inherited
int get hashCodeThe hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Inherited from Object.
Implementation
dart
external int get hashCode;headers no setter
HttpHeaders get headersReturns the response headers.
The response headers can be modified until the response body is written to or closed. After that they become immutable.
Implementation
dart
HttpHeaders get headers;persistentConnection read / write
bool persistentConnectiongetter:
Gets and sets the persistent connection state. The initial value of this property is the persistent connection state from the request.
setter:
Gets and sets the persistent connection state. The initial value of this property is the persistent connection state from the request.
Implementation
dart
late bool persistentConnection;reasonPhrase read / write
String reasonPhrasegetter:
The reason phrase for the response.
If no reason phrase is explicitly set, a default reason phrase is provided.
The reason phrase must be set before the body is written to. Setting the reason phrase after writing to the response body or closing the response will throw a StateError.
setter:
The reason phrase for the response.
If no reason phrase is explicitly set, a default reason phrase is provided.
The reason phrase must be set before the body is written to. Setting the reason phrase after writing to the response body or closing the response will throw a StateError.
Implementation
dart
late String reasonPhrase;runtimeType no setter inherited
Type get runtimeTypeA representation of the runtime type of the object.
Inherited from Object.
Implementation
dart
external Type get runtimeType;statusCode read / write
int statusCodegetter:
The status code of the response.
Any integer value is accepted. For the official HTTP status codes use the fields from HttpStatus. If no status code is explicitly set the default value HttpStatus.ok is used.
The status code must be set before the body is written to. Setting the status code after writing to the response body or closing the response will throw a StateError.
setter:
The status code of the response.
Any integer value is accepted. For the official HTTP status codes use the fields from HttpStatus. If no status code is explicitly set the default value HttpStatus.ok is used.
The status code must be set before the body is written to. Setting the status code after writing to the response body or closing the response will throw a StateError.
Implementation
dart
int statusCode = HttpStatus.ok;Methods
add() inherited
Adds byte data to the target consumer, ignoring encoding.
The encoding does not apply to this method, and the data list is passed directly to the target consumer as a stream event.
This method must not be called when a stream is currently being added using addStream.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
The data list should not be modified after it has been passed to add because it is not defined whether the target consumer will receive the list in the original or modified state.
Individual values in data which are not in the range 0 .. 255 will be truncated to their low eight bits, as if by int.toUnsigned, before being used.
Inherited from IOSink.
Implementation
dart
void add(List<int> data);addError() inherited
void addError(Object error, [StackTrace? stackTrace])Passes the error to the target consumer as an error event.
This method must not be called when a stream is currently being added using addStream.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
Inherited from IOSink.
Implementation
dart
void addError(error, [StackTrace? stackTrace]);addStream() inherited
Adds all elements of the given stream.
Returns a Future that completes when all elements of the given stream have been added.
If the stream contains an error, the addStream ends at the error, and the returned future completes with that error.
This method must not be called when a stream is currently being added using this method.
Individual values in the lists emitted by stream which are not in the range 0 .. 255 will be truncated to their low eight bits, as if by int.toUnsigned, before being used.
Inherited from IOSink.
Implementation
dart
Future addStream(Stream<List<int>> stream);close() inherited
Future<dynamic> close()Close the target consumer.
NOTE: Writes to the IOSink may be buffered, and may not be flushed by a call to close(). To flush all buffered writes, call flush() before calling close().
Inherited from IOSink.
Implementation
dart
Future close();detachSocket()
Detaches the underlying socket from the HTTP server. When the socket is detached the HTTP server will no longer perform any operations on it.
This is normally used when an HTTP upgrade request is received and the communication should continue with a different protocol.
If writeHeaders is true, the status line and headers will be written to the socket before it's detached. If false, the socket is detached immediately, without any data written to the socket. Default is true.
Implementation
dart
Future<Socket> detachSocket({bool writeHeaders = true});flush() inherited
Future<dynamic> flush()Returns a Future that completes once all buffered data is accepted by the underlying StreamConsumer.
This method must not be called while an addStream is incomplete.
NOTE: This is not necessarily the same as the data being flushed by the operating system.
Inherited from IOSink.
Implementation
dart
Future flush();noSuchMethod() inherited
dynamic noSuchMethod(Invocation invocation)Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time errorThis invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
dart
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.
If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);redirect()
Respond with a redirect to location.
The URI in location should be absolute, but there are no checks to enforce that.
By default the HTTP status code HttpStatus.movedTemporarily (302) is used for the redirect, but an alternative one can be specified using the status argument.
This method will also call close, and the returned future is the future returned by close.
Implementation
dart
Future redirect(Uri location, {int status = HttpStatus.movedTemporarily});toString() inherited
String toString()A string representation of this object.
Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.
Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.
Inherited from Object.
Implementation
dart
external String toString();write() inherited
void write(Object? object)Converts object to a String by invoking Object.toString and adds the encoding of the result to the target consumer.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
Inherited from IOSink.
Implementation
dart
void write(Object? object);writeAll() inherited
Iterates over the given objects and writes them in sequence.
If separator is provided, a write with the separator is performed between any two elements of objects.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
Inherited from IOSink.
Implementation
dart
void writeAll(Iterable objects, [String separator = ""]);writeCharCode() inherited
void writeCharCode(int charCode)Writes the character of charCode.
This method is equivalent to write(String.fromCharCode(charCode)).
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
Inherited from IOSink.
Implementation
dart
void writeCharCode(int charCode);writeln() inherited
void writeln([Object? object = ""])Converts object to a String by invoking Object.toString and writes the result to this, followed by a newline.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
Inherited from IOSink.
Implementation
dart
void writeln([Object? object = ""]);Operators
operator ==() inherited
The equality operator.
The default behavior for all Objects is to return true if and only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false.Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
dart
external bool operator ==(Object other);