HttpClient class - dart:io library (original) (raw)
An HTTP client for communicating with an HTTP server.
Note: You should avoid directly using
HttpClient
to make HTTP requests. You can useHttpClient
indirectly through theIOClientadapter in package:http.Using a higher-level library, like package:http, allows you to switch implementations with minimal changes to your code. For example,
package:http
Clienthas implementations for the browser and implementations that use platform native HTTP clients on Android and iOS. UnlikeHttpClient
, these native implementations work with the proxies, VPNs, etc.
Sends HTTP requests to an HTTP server and receives responses. Maintains state, including session cookies and other cookies, between multiple requests to the same server.
HttpClient contains a number of methods to send an HttpClientRequestto an Http server and receive an HttpClientResponse back. For example, you can use the get, getUrl, post, and postUrl methods for GET and POST requests, respectively.
Making a simple GET request: an example
A getUrl
request is a two-step process, triggered by two Futures. When the first future completes with an HttpClientRequest, the underlying network connection has been established, but no data has been sent. In the callback function for the first future, the HTTP headers and body can be set on the request. Either the first write to the request object or a call to close sends the request to the server.
When the HTTP response is received from the server, the second future, which is returned by close, completes with an HttpClientResponse object. This object provides access to the headers and body of the response. The body is available as a stream implemented by HttpClientResponse
. If a body is present, it must be read. Otherwise, it leads to resource leaks. Consider using HttpClientResponse.drain if the body is unused.
var client = HttpClient();
try {
HttpClientRequest request = await client.get('localhost', 80, '/file.txt');
// Optionally set up headers...
// Optionally write to the request object...
HttpClientResponse response = await request.close();
// Process the response
final stringData = await response.transform(utf8.decoder).join();
print(stringData);
} finally {
client.close();
}
The future for HttpClientRequest is created by methods such asgetUrl and open.
HTTPS connections
An HttpClient
can make HTTPS requests, connecting to a server using the TLS (SSL) secure networking protocol. Calling getUrl with an https: scheme will work automatically, if the server's certificate is signed by a root CA (certificate authority) on the default list of well-known trusted CAs, compiled by Mozilla.
To add a custom trusted certificate authority, or to send a client certificate to servers that request one, pass a SecurityContext object as the optional context
argument to the HttpClient
constructor. The desired security options can be set on the SecurityContext object.
All HttpClient
requests set the following header by default:
Accept-Encoding: gzip
This allows the HTTP server to use gzip compression for the body if possible. If this behavior is not desired set theAccept-Encoding
header to something else. To turn off gzip compression of the response, clear this header:
request.headers.removeAll(HttpHeaders.acceptEncodingHeader)
Closing the HttpClient
HttpClient
supports persistent connections and caches network connections to reuse them for multiple requests whenever possible. This means that network connections can be kept open for some time after a request has completed. Use HttpClient.closeto force the HttpClient
object to shut down and to close the idle network connections.
Turning proxies on and off
By default the HttpClient
uses the proxy configuration available from the environment, see findProxyFromEnvironment. To turn off the use of proxies set the findProxy property to null
.
HttpClient client = HttpClient();
client.findProxy = null;
Constructors
HttpClient({SecurityContext? context})
factory
Properties
authenticate ← Future<bool> Function(Uri url, String scheme, String? realm)?
Sets the function to be called when a site is requesting authentication.
no getter
authenticateProxy ← Future<bool> Function(String host, int port, String scheme, String? realm)?
Sets the function to be called when a proxy is requesting authentication.
no getter
Gets and sets whether the body of a response will be automatically uncompressed.
getter/setter pair
badCertificateCallback ← bool Function(X509Certificate cert, String host, int port)?
Sets a callback that will decide whether to accept a secure connection with a server certificate that cannot be authenticated by any of our trusted root certificates.
no getter
connectionFactory ← Future<ConnectionTask<Socket>> Function(Uri url, String? proxyHost, int? proxyPort)?
Sets the function used to create socket connections.
no getter
Gets and sets the connection timeout.
getter/setter pair
findProxy ← String Function(Uri url)?
Sets the function used to resolve the proxy server to be used for opening a HTTP connection to the specified url
. If this function is not set, direct connections will always be used.
no getter
The hash code for this object.
no setterinherited
Gets and sets the idle timeout of non-active persistent (keep-alive) connections.
getter/setter pair
keyLog ← dynamic Function(String line)?
Sets a callback that will be called when new TLS keys are exchanged with the server. It will receive one line of text inNSS Key Log Formatfor each call. Writing these lines to a file will allow tools (such asWireshark) to decrypt communication between the this client and the server. This is meant to allow network-level debugging of secure sockets and should not be used in production code. For example:
no getter
Gets and sets the maximum number of live connections, to a single host.
getter/setter pair
A representation of the runtime type of the object.
no setterinherited
Gets and sets the default value of the User-Agent
header for all requests generated by this HttpClient.
getter/setter pair
Methods
addCredentials(Uri url, String realm, HttpClientCredentials credentials)→ void
Add credentials to be used for authorizing HTTP requests.
addProxyCredentials(String host, int port, String realm, HttpClientCredentials credentials)→ void
Add credentials to be used for authorizing HTTP proxies.
close({bool force = false})→ void
Shuts down the HTTP client.
delete(String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection using the DELETE method.
deleteUrl(Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection using the DELETE method.
get(String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection using the GET method.
getUrl(Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection using the GET method.
head(String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection using the HEAD method.
headUrl(Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection using the HEAD method.
noSuchMethod(Invocation invocation)→ dynamic
Invoked when a nonexistent method or property is accessed.
inherited
open(String method, String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection.
openUrl(String method, Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection.
patch(String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection using the PATCH method.
patchUrl(Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection using the PATCH method.
post(String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection using the POST method.
postUrl(Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection using the POST method.
put(String host, int port, String path)→ Future<HttpClientRequest>
Opens a HTTP connection using the PUT method.
putUrl(Uri url)→ Future<HttpClientRequest>
Opens a HTTP connection using the PUT method.
A string representation of this object.
inherited
Operators
operator ==(Object other)→ bool
The equality operator.
inherited
Static Properties
Current state of HTTP request logging from all HttpClients to the developer timeline.
getter/setter pair
Static Methods
findProxyFromEnvironment(Uri url, {Map<String, String>? environment})→ String
Function for resolving the proxy server to be used for a HTTP connection from the proxy configuration specified through environment variables.
Constants
defaultHttpPort → const int
defaultHttpsPort → const int