HttpClientRequest abstract interface#
HTTP request for a client connection.
To set up a request, set the headers using the headers property
provided in this class and write the data to the body of the request.
HttpClientRequest is an IOSink. Use the methods from IOSink,
such as writeCharCode(), to write the body of the HTTP
request. 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.
When writing string data through the IOSink the encoding used is determined from the "charset" parameter of the "Content-Type" header.
var client = HttpClient();
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
request.headers.contentType =
ContentType('application', 'json', charset: 'utf-8');
request.write('text content👍🎯'); // Strings written will be UTF-8 encoded.
If no charset is provided the default of ISO-8859-1 (Latin 1) is used.
var client = HttpClient();
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
request.headers.add(HttpHeaders.contentTypeHeader, "text/plain");
request.write('blåbærgrød'); // Strings written will be ISO-8859-1 encoded
An exception is thrown if you use an unsupported encoding and the
write() method being used takes a string parameter.
Implemented types
Properties#
bufferOutput read / write#
getter:
Gets or sets if the HttpClientRequest 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 HttpClientRequest 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
bool bufferOutput = true;
connectionInfo no setter#
Gets information about the client connection.
Returns null if the socket is not available.
Implementation
HttpConnectionInfo? get connectionInfo;
contentLength read / write#
getter:
Gets and sets the content length of the request.
If the size of the request is not known in advance set content length to -1, which is also the default.
setter:
Gets and sets the content length of the request.
If the size of the request is not known in advance set content length to -1, which is also the default.
Implementation
int contentLength = -1;
cookies no setter#
Cookies to present to the server (in the 'cookie' header).
Implementation
List<Cookie> get cookies;
done no setter override#
An HttpClientResponse
future that will complete once the response is
available.
If an error occurs before the response is available, this future will complete with an error.
Implementation
Future<HttpClientResponse> get done;
encoding read / write inherited#
getter:
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
late Encoding encoding;
followRedirects read / write#
getter:
Whether to follow redirects automatically.
Set this property to false if this request should not
automatically follow redirects. The default is true.
Automatic redirect will only happen for "GET" and "HEAD" requests and only for the status codes HttpStatus.movedPermanently (301), HttpStatus.found (302), HttpStatus.movedTemporarily (302, alias for HttpStatus.found), HttpStatus.seeOther (303), HttpStatus.temporaryRedirect (307) and HttpStatus.permanentRedirect (308). For HttpStatus.seeOther (303) automatic redirect will also happen for "POST" requests with the method changed to "GET" when following the redirect.
All headers added to the request will be added to the redirection request(s) except when forwarding sensitive headers like "Authorization", "WWW-Authenticate", and "Cookie". Those headers will be skipped if following a redirect to a domain that is not a subdomain match or exact match of the initial domain. For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" will forward the sensitive headers, but a redirect to "bar.com" will not.
Any body send with the request will not be part of the redirection request(s).
For precise control of redirect handling, set this property to false
and make a separate HTTP request to process the redirect. For example:
final client = HttpClient();
var uri = Uri.parse("http://localhost/");
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
while (response.isRedirect) {
response.drain();
final location = response.headers.value(HttpHeaders.locationHeader);
if (location != null) {
uri = uri.resolve(location);
request = await client.getUrl(uri);
// Set the body or headers as desired.
request.followRedirects = false;
response = await request.close();
}
}
// Do something with the final response.
setter:
Whether to follow redirects automatically.
Set this property to false if this request should not
automatically follow redirects. The default is true.
Automatic redirect will only happen for "GET" and "HEAD" requests and only for the status codes HttpStatus.movedPermanently (301), HttpStatus.found (302), HttpStatus.movedTemporarily (302, alias for HttpStatus.found), HttpStatus.seeOther (303), HttpStatus.temporaryRedirect (307) and HttpStatus.permanentRedirect (308). For HttpStatus.seeOther (303) automatic redirect will also happen for "POST" requests with the method changed to "GET" when following the redirect.
All headers added to the request will be added to the redirection request(s) except when forwarding sensitive headers like "Authorization", "WWW-Authenticate", and "Cookie". Those headers will be skipped if following a redirect to a domain that is not a subdomain match or exact match of the initial domain. For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" will forward the sensitive headers, but a redirect to "bar.com" will not.
Any body send with the request will not be part of the redirection request(s).
For precise control of redirect handling, set this property to false
and make a separate HTTP request to process the redirect. For example:
final client = HttpClient();
var uri = Uri.parse("http://localhost/");
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
while (response.isRedirect) {
response.drain();
final location = response.headers.value(HttpHeaders.locationHeader);
if (location != null) {
uri = uri.resolve(location);
request = await client.getUrl(uri);
// Set the body or headers as desired.
request.followRedirects = false;
response = await request.close();
}
}
// Do something with the final response.
Implementation
bool followRedirects = true;
hashCode no setter inherited#
The 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
external int get hashCode;
headers no setter#
Returns the client request headers.
The client request headers can be modified until the client request body is written to or closed. After that they become immutable.
Implementation
HttpHeaders get headers;
maxRedirects read / write#
getter:
Set this property to the maximum number of redirects to follow
when followRedirects
is true. If this number is exceeded
an error event will be added with a RedirectException.
The default value is 5.
setter:
Set this property to the maximum number of redirects to follow
when followRedirects
is true. If this number is exceeded
an error event will be added with a RedirectException.
The default value is 5.
Implementation
int maxRedirects = 5;
method no setter#
The method of the request.
Implementation
String get method;
persistentConnection read / write#
getter:
The requested persistent connection state.
The default value is true.
setter:
The requested persistent connection state.
The default value is true.
Implementation
bool persistentConnection = true;
runtimeType no setter inherited#
A representation of the runtime type of the object.
Inherited from Object.
Implementation
external Type get runtimeType;
uri no setter#
The uri of the request.
Implementation
Uri get uri;
Methods#
abort()#
Aborts the client connection.
If the connection has not yet completed, the request is aborted and the
done
future (also returned by close) is completed with the provided
exception and stackTrace.
If exception is omitted, it defaults to an HttpException, and if
stackTrace is omitted, it defaults to StackTrace.empty.
If the done future has already completed, aborting has no effect.
Using the IOSink methods (e.g., write and add) has no effect after the request has been aborted
var client = HttpClient();
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
request.write('request content');
Timer(Duration(seconds: 1), () {
request.abort();
});
request.close().then((response) {
// If response comes back before abort, this callback will be called.
}, onError: (e) {
// If abort() called before response is available, onError will fire.
});
Implementation
void abort([Object? exception, StackTrace? stackTrace]);
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
void add(List<int> data);
addError() inherited#
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
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
Future addStream(Stream<List<int>> stream);
close() override#
Close the request for input. Returns the value of done.
Implementation
Future<HttpClientResponse> close();
flush() inherited#
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
Future flush();
noSuchMethod() inherited#
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:
dynamic object = 1;
object.add(42); // Statically allowed, run-time error
This 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:
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
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
toString() inherited#
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
external String toString();
write() inherited#
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
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
void writeAll(Iterable objects, [String separator = ""]);
writeCharCode() inherited#
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
void writeCharCode(int charCode);
writeln() inherited#
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
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
external bool operator ==(Object other);